vasp module#
VASP calculator interface for ASE.
This package provides a modern Python interface to VASP (Vienna Ab initio Simulation Package) through ASE (Atomic Simulation Environment).
Features: - Full VASP parameter support via keyword arguments - Automatic input file generation - Result parsing from output files - Pluggable execution backends (local, SLURM, Kubernetes) - Non-blocking async execution with exception-based signaling - Workflow tool integration (Prefect, Dask, Parsl, Covalent) - Parameter presets for common calculation types - quacc-style recipes for automated workflows
Example
>>> from ase.build import bulk
>>> from vasp import Vasp
>>>
>>> atoms = bulk('Si')
>>> calc = Vasp(
... 'si_calc',
... atoms=atoms,
... xc='PBE',
... encut=400,
... kpts=(8, 8, 8),
... )
>>>
>>> energy = calc.potential_energy
>>> print(f"Energy: {energy:.3f} eV")
- Non-blocking usage:
>>> from vasp.exceptions import VaspSubmitted, VaspQueued >>> from vasp.runners import SlurmRunner >>> >>> runner = SlurmRunner(partition='compute', nodes=2) >>> calc = Vasp('my_calc', atoms=atoms, runner=runner) >>> >>> try: ... energy = calc.potential_energy ... except VaspSubmitted as e: ... print(f"Job submitted: {e.jobid}")
- Using parameter presets:
>>> from vasp.parameters import get_vdw_params, get_ldau_params >>> >>> # Add D3-BJ dispersion correction >>> vdw = get_vdw_params('d3bj') >>> calc = Vasp(..., **vdw) >>> >>> # DFT+U for Fe oxide >>> ldau = get_ldau_params(['Fe', 'O'], {'Fe': 4.0}) >>> calc = Vasp(..., **ldau)
- Using recipes:
>>> from vasp.recipes import relax_job, static_job, phonon_flow >>> >>> result = relax_job(atoms, relax_cell=True) >>> phonons = phonon_flow(result.atoms, supercell_matrix=(2, 2, 2))
- class vasp.Vasp(label='vasp', atoms=None, runner=None, force=False, **kwargs)[source]#
Bases:
Calculator,IOMixin,ElectronicMixin,AnalysisMixin,DynamicsMixinASE calculator interface for VASP.
This calculator provides a complete interface to VASP through ASE, with support for: - All standard VASP parameters as keyword arguments - Automatic input file generation - Result parsing from output files - Pluggable execution backends (local, SLURM, Kubernetes) - Non-blocking async execution with exception-based signaling
- Parameters:
label (str) – Calculation directory path (default: ‘vasp’).
atoms (Atoms | list[Atoms] | None) – ASE Atoms object for the calculation.
runner (Runner | None) – Execution backend (default: LocalRunner).
xc – Exchange-correlation functional (e.g., ‘PBE’, ‘HSE06’).
pp – Pseudopotential type (e.g., ‘PBE’, ‘LDA’).
kpts – K-point grid as (nx, ny, nz) tuple.
gamma – Use Gamma-centered k-point grid.
setups – Dict of special POTCAR setups per element.
**kwargs – Any VASP INCAR parameters.
force (bool)
Example
>>> from ase.build import bulk >>> from vasp import Vasp >>> >>> atoms = bulk('Si') >>> calc = Vasp( ... 'si_calc', ... atoms=atoms, ... xc='PBE', ... encut=400, ... kpts=(8, 8, 8), ... ) >>> >>> energy = calc.potential_energy >>> print(f"Energy: {energy:.3f} eV")
- Non-blocking usage:
>>> from vasp.exceptions import VaspSubmitted, VaspQueued >>> >>> try: ... energy = calc.potential_energy ... except VaspSubmitted as e: ... print(f"Job submitted: {e.jobid}") ... except VaspQueued: ... print("Waiting in queue...")
- name = 'vasp'#
- implemented_properties: List[str] = ['energy', 'forces', 'stress', 'magmom', 'magmoms', 'dipole']#
Properties calculator can handle (energy, forces, …)
- default_parameters: dict[str, Any] = {'gamma': False, 'ismear': 1, 'kpts': (1, 1, 1), 'lcharg': False, 'lwave': False, 'pp': 'PBE', 'sigma': 0.1, 'xc': 'PBE'}#
Default parameters
- set(**kwargs)[source]#
Set calculator parameters.
- Parameters:
**kwargs – Parameters to update.
- Returns:
Dict of changed parameters.
- Return type:
- calculate(atoms=None, properties=None, system_changes=None)[source]#
Run VASP calculation.
This method triggers the VASP calculation. Depending on the runner configuration, it may: - Run VASP and wait for completion (LocalRunner, blocking) - Submit job and raise exception (SLURM, K8s runners)
- Parameters:
- Raises:
VaspSubmitted – Job was just submitted.
VaspQueued – Job is in queue.
VaspRunning – Job is currently running.
VaspNotConverged – Calculation failed to converge.
- Return type:
None
- update()[source]#
Ensure calculation results are current.
Checks status and reads results if complete. Raises exceptions for non-complete states.
- Return type:
None
- get_forces(atoms=None)[source]#
Get forces on atoms.
- Parameters:
atoms (Atoms | None) – Atoms object (triggers calculation if different).
- Returns:
Forces array of shape (natoms, 3) in eV/Angstrom.
- Return type:
np.ndarray
- get_stress(atoms=None)[source]#
Get stress tensor.
- Parameters:
atoms (Atoms | None) – Atoms object (triggers calculation if different).
- Returns:
Stress in Voigt notation (6,) in eV/Angstrom^3.
- Return type:
np.ndarray
- submit()[source]#
Submit calculation without blocking.
Writes input files and submits to runner. Returns job ID if applicable.
- Returns:
Job ID string, or None for local runner.
- Return type:
str | None
- poll()[source]#
Check calculation status without triggering anything.
- Returns:
JobStatus with current state.
- Return type:
- is_complete()[source]#
Check if calculation is complete.
- Returns:
True if calculation finished successfully.
- Return type:
- run_async()[source]#
Run calculation with result object instead of exceptions.
Useful for workflow tools that prefer return values.
- Returns:
CalculationResult with state and results.
- Return type:
Example
>>> result = calc.run_async() >>> if result.state == JobState.COMPLETE: ... print(result.energy)
- cancel()[source]#
Cancel running calculation.
- Returns:
True if cancellation successful.
- Return type:
- clone(label, copy_wavecar=False, copy_chgcar=False)[source]#
Create a new calculator with same parameters but different directory.
- set_nbands(f=1.5)[source]#
Set NBANDS based on valence electrons with a multiplier.
VASP default is approximately NELECT/2 + NIONS/2. This method sets NBANDS = f * default.
- Parameters:
f (float) – Multiplier for default number of bands.
- Returns:
The number of bands set.
- Raises:
ValueError – If atoms not set or POTCAR info unavailable.
- Return type:
- stop_if(condition, message='Calculation stopped')[source]#
Stop execution if condition is True.
Useful for checking if results are valid before proceeding.
- Parameters:
- Raises:
SystemExit – If condition is True.
- Return type:
None
- class vasp.CalculationResult(state, energy=None, forces=None, stress=None, jobid=None, error=None)[source]#
Bases:
objectContainer for workflow-friendly calculation results.
Use with calc.run_async() for exception-free status checking.
- Parameters:
- state#
Current job state.
- forces#
Forces array (if complete).
- Type:
numpy.ndarray | None
- stress#
Stress tensor (if complete).
- Type:
numpy.ndarray | None
- exception vasp.VaspSubmitted(message='Job submitted', jobid=None)[source]#
Bases:
VaspExceptionRaised when a job has just been submitted.
- jobid#
The job identifier from the scheduler.
- message#
Additional status message.
- exception vasp.VaspQueued(message='Queued', jobid=None)[source]#
Bases:
VaspExceptionRaised when a job is waiting in the queue.
- jobid#
The job identifier.
- message#
Additional status message.
- exception vasp.VaspRunning(message='Running', jobid=None)[source]#
Bases:
VaspExceptionRaised when a job is currently executing.
- jobid#
The job identifier.
- message#
Additional status message.
- exception vasp.VaspNotFinished(message='Calculation not finished')[source]#
Bases:
VaspExceptionRaised when a calculation started but is not complete.
This can indicate the job is still running or was interrupted.
- Parameters:
message (str)
- exception vasp.VaspNotConverged(message='Calculation did not converge')[source]#
Bases:
VaspExceptionRaised when a calculation did not converge.
This typically means the electronic or ionic relaxation did not reach the specified convergence criteria.
- Parameters:
message (str)
- exception vasp.VaspError(message='VASP error')[source]#
Bases:
VaspExceptionRaised when VASP encounters an error during calculation.
This indicates a fatal error in the VASP run, such as incorrect input parameters or numerical instabilities.
- Parameters:
message (str)
- exception vasp.VaspEmptyOutput(message='Empty or missing output')[source]#
Bases:
VaspExceptionRaised when expected output files are empty or missing.
This can happen if VASP crashed before writing output or if the CONTCAR is empty after a failed relaxation.
- Parameters:
message (str)
- exception vasp.VaspSetupError(message='Setup error')[source]#
Bases:
VaspExceptionRaised when there’s an error in calculation setup.
This includes missing POTCAR files, invalid parameters, or configuration errors.
- Parameters:
message (str)
- exception vasp.VaspWarning[source]#
Bases:
UserWarningWarning for non-fatal issues that may affect results.
These are issues that don’t prevent the calculation from completing but may indicate problems with the results.
- class vasp.Runner[source]#
Bases:
ABCAbstract base class for VASP execution backends.
Runners handle submitting and monitoring VASP calculations. They are designed for non-blocking operation: - run() submits/starts a job and returns immediately - status() checks current state without blocking - Exceptions signal state transitions to calling code
Subclasses must implement: - run(): Submit or start a calculation - status(): Check current job status
Example
>>> runner = LocalRunner(vasp_command='vasp_std') >>> status = runner.run('/path/to/calc') >>> if status.state == JobState.COMPLETE: ... print("Done!")
- abstract run(directory)[source]#
Start or submit a VASP calculation.
This method should NOT block waiting for completion. For async runners (SLURM, K8s), it submits the job. For local runners, behavior depends on configuration.
- Parameters:
directory (str) – Path to calculation directory containing input files.
- Returns:
JobStatus with current state after submission.
- Raises:
VaspSubmitted – Job was just submitted (contains jobid).
VaspQueued – Job is already queued.
VaspRunning – Job is currently running.
VaspSetupError – Input files missing or invalid.
- Return type:
- abstract status(directory)[source]#
Check status of a calculation without blocking.
This method never starts a new calculation. It only reports the current state based on job scheduler status and output files.
- wait(directory, timeout=None, poll_interval=30.0)[source]#
Block until calculation completes (for interactive use).
This is a convenience method that polls status() until the job is done. For most workflows, you should use status() directly with your own retry logic.
- Parameters:
- Returns:
Final JobStatus.
- Raises:
TimeoutError – If timeout is reached before completion.
- Return type:
- class vasp.JobState(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
Bases:
EnumPossible states of a VASP calculation.
- NOT_STARTED = 'not_started'#
- SUBMITTED = 'submitted'#
- QUEUED = 'queued'#
- RUNNING = 'running'#
- COMPLETE = 'complete'#
- FAILED = 'failed'#
- UNKNOWN = 'unknown'#
- class vasp.JobStatus(state, jobid=None, message=None, metadata=<factory>)[source]#
Bases:
objectStatus information for a VASP calculation.
- state#
Current state of the job.
- class vasp.LocalRunner(vasp_executable=None, nprocs='auto', mpi_command='mpirun', mpi_extra_args=None, background=False, vasp_command=None)[source]#
Bases:
RunnerRun VASP on the local machine.
By default runs synchronously (blocking until complete). Use background=True for non-blocking execution.
The runner intelligently determines the number of MPI processes: - If nprocs=’auto’ (default): detects based on CPUs and system size - If nprocs is an int: uses that exact number - Respects NCORE settings in INCAR
Environment variables (in order of precedence): - VASP_EXECUTABLE: Path to VASP binary (e.g., /opt/vasp/bin/vasp_std) - VASP_COMMAND: Full command (legacy, e.g., ‘mpirun -np 8 vasp_std’) - VASP_NPROCS: Number of MPI processes (or ‘auto’) - VASP_MPI_EXTRA_ARGS: Extra MPI arguments (e.g., ‘–map-by hwthread’)
- Parameters:
vasp_executable (str | None) – Path to VASP binary. Defaults to $VASP_EXECUTABLE, then extracts from $VASP_COMMAND, or ‘vasp_std’.
nprocs (int | str) – Number of MPI processes. ‘auto’ (default) detects optimal count, or specify an integer. Set to 1 for serial execution.
mpi_command (str | None) – MPI launcher (default: ‘mpirun’). Set to None to disable MPI and run serial VASP.
mpi_extra_args (str | None) – Extra arguments for MPI launcher.
background (bool) – If True, run in background and return immediately.
vasp_command (str | None)
Example
>>> # Auto-detect optimal parallelization >>> runner = LocalRunner() >>> calc = Vasp('my_calc', runner=runner, ...)
>>> # Specify exact process count >>> runner = LocalRunner(nprocs=16)
>>> # Serial execution (no MPI) >>> runner = LocalRunner(nprocs=1, mpi_command=None)
>>> # Custom MPI settings >>> runner = LocalRunner( ... nprocs=8, ... mpi_extra_args='--bind-to core --map-by socket' ... )
- run(directory)[source]#
Run VASP in the specified directory.
- Parameters:
directory (str) – Path to calculation directory with input files.
- Returns:
JobStatus indicating outcome.
- Raises:
VaspRunning – If background=True and job is still running.
VaspSetupError – If required input files are missing.
- Return type:
- class vasp.MockRunner(results=None, energy=None, forces=None, stress=None, state_sequence=None, delay_calls=0, delay=0, fail_on_run=False, error_message='Mock error', write_outputs=True)[source]#
Bases:
RunnerMock runner for testing without VASP.
Simulates VASP execution by writing fake output files. Useful for testing calculator logic, workflow integration, and development when VASP is not available.
- Parameters:
results (MockResults | None) – MockResults object with calculation outputs.
energy (float | None) – Shortcut to set results.energy.
forces (list | np.ndarray | None) – Shortcut to set results.forces.
state_sequence (list[JobState] | None) – List of JobStates to cycle through on each status() call. Useful for testing async workflows.
delay_calls (int) – Number of status() calls before returning COMPLETE. Alternative to state_sequence for simple cases.
fail_on_run (bool) – If True, immediately fail when run() is called.
error_message (str) – Error message if fail_on_run is True.
write_outputs (bool) – If True, write mock OUTCAR/vasprun.xml files.
stress (list | np.ndarray | None)
delay (float)
Example
>>> # Simple successful calculation >>> runner = MockRunner(energy=-15.3) >>> >>> # Simulate job that takes 3 status checks to complete >>> runner = MockRunner( ... energy=-15.3, ... state_sequence=[ ... JobState.QUEUED, ... JobState.RUNNING, ... JobState.RUNNING, ... JobState.COMPLETE, ... ] ... ) >>> >>> # Simulate failed calculation >>> runner = MockRunner(fail_on_run=True, error_message="ZBRENT error")
Calculator#
- class vasp.Vasp(label='vasp', atoms=None, runner=None, force=False, **kwargs)[source]#
Bases:
Calculator,IOMixin,ElectronicMixin,AnalysisMixin,DynamicsMixinASE calculator interface for VASP.
This calculator provides a complete interface to VASP through ASE, with support for: - All standard VASP parameters as keyword arguments - Automatic input file generation - Result parsing from output files - Pluggable execution backends (local, SLURM, Kubernetes) - Non-blocking async execution with exception-based signaling
- Parameters:
label (str) – Calculation directory path (default: ‘vasp’).
atoms (Atoms | list[Atoms] | None) – ASE Atoms object for the calculation.
runner (Runner | None) – Execution backend (default: LocalRunner).
xc – Exchange-correlation functional (e.g., ‘PBE’, ‘HSE06’).
pp – Pseudopotential type (e.g., ‘PBE’, ‘LDA’).
kpts – K-point grid as (nx, ny, nz) tuple.
gamma – Use Gamma-centered k-point grid.
setups – Dict of special POTCAR setups per element.
**kwargs – Any VASP INCAR parameters.
force (bool)
Example
>>> from ase.build import bulk >>> from vasp import Vasp >>> >>> atoms = bulk('Si') >>> calc = Vasp( ... 'si_calc', ... atoms=atoms, ... xc='PBE', ... encut=400, ... kpts=(8, 8, 8), ... ) >>> >>> energy = calc.potential_energy >>> print(f"Energy: {energy:.3f} eV")
- Non-blocking usage:
>>> from vasp.exceptions import VaspSubmitted, VaspQueued >>> >>> try: ... energy = calc.potential_energy ... except VaspSubmitted as e: ... print(f"Job submitted: {e.jobid}") ... except VaspQueued: ... print("Waiting in queue...")
- name = 'vasp'#
- implemented_properties: List[str] = ['energy', 'forces', 'stress', 'magmom', 'magmoms', 'dipole']#
Properties calculator can handle (energy, forces, …)
- default_parameters: dict[str, Any] = {'gamma': False, 'ismear': 1, 'kpts': (1, 1, 1), 'lcharg': False, 'lwave': False, 'pp': 'PBE', 'sigma': 0.1, 'xc': 'PBE'}#
Default parameters
- set(**kwargs)[source]#
Set calculator parameters.
- Parameters:
**kwargs – Parameters to update.
- Returns:
Dict of changed parameters.
- Return type:
- calculate(atoms=None, properties=None, system_changes=None)[source]#
Run VASP calculation.
This method triggers the VASP calculation. Depending on the runner configuration, it may: - Run VASP and wait for completion (LocalRunner, blocking) - Submit job and raise exception (SLURM, K8s runners)
- Parameters:
- Raises:
VaspSubmitted – Job was just submitted.
VaspQueued – Job is in queue.
VaspRunning – Job is currently running.
VaspNotConverged – Calculation failed to converge.
- Return type:
None
- update()[source]#
Ensure calculation results are current.
Checks status and reads results if complete. Raises exceptions for non-complete states.
- Return type:
None
- get_forces(atoms=None)[source]#
Get forces on atoms.
- Parameters:
atoms (Atoms | None) – Atoms object (triggers calculation if different).
- Returns:
Forces array of shape (natoms, 3) in eV/Angstrom.
- Return type:
np.ndarray
- get_stress(atoms=None)[source]#
Get stress tensor.
- Parameters:
atoms (Atoms | None) – Atoms object (triggers calculation if different).
- Returns:
Stress in Voigt notation (6,) in eV/Angstrom^3.
- Return type:
np.ndarray
- submit()[source]#
Submit calculation without blocking.
Writes input files and submits to runner. Returns job ID if applicable.
- Returns:
Job ID string, or None for local runner.
- Return type:
str | None
- poll()[source]#
Check calculation status without triggering anything.
- Returns:
JobStatus with current state.
- Return type:
- is_complete()[source]#
Check if calculation is complete.
- Returns:
True if calculation finished successfully.
- Return type:
- run_async()[source]#
Run calculation with result object instead of exceptions.
Useful for workflow tools that prefer return values.
- Returns:
CalculationResult with state and results.
- Return type:
Example
>>> result = calc.run_async() >>> if result.state == JobState.COMPLETE: ... print(result.energy)
- cancel()[source]#
Cancel running calculation.
- Returns:
True if cancellation successful.
- Return type:
- clone(label, copy_wavecar=False, copy_chgcar=False)[source]#
Create a new calculator with same parameters but different directory.
- set_nbands(f=1.5)[source]#
Set NBANDS based on valence electrons with a multiplier.
VASP default is approximately NELECT/2 + NIONS/2. This method sets NBANDS = f * default.
- Parameters:
f (float) – Multiplier for default number of bands.
- Returns:
The number of bands set.
- Raises:
ValueError – If atoms not set or POTCAR info unavailable.
- Return type:
- stop_if(condition, message='Calculation stopped')[source]#
Stop execution if condition is True.
Useful for checking if results are valid before proceeding.
- Parameters:
- Raises:
SystemExit – If condition is True.
- Return type:
None
Exceptions#
- exception vasp.VaspSubmitted(message='Job submitted', jobid=None)[source]#
Raised when a job has just been submitted.
- jobid#
The job identifier from the scheduler.
- message#
Additional status message.
- exception vasp.VaspQueued(message='Queued', jobid=None)[source]#
Raised when a job is waiting in the queue.
- jobid#
The job identifier.
- message#
Additional status message.
- exception vasp.VaspRunning(message='Running', jobid=None)[source]#
Raised when a job is currently executing.
- jobid#
The job identifier.
- message#
Additional status message.
- exception vasp.VaspNotFinished(message='Calculation not finished')[source]#
Raised when a calculation started but is not complete.
This can indicate the job is still running or was interrupted.
- Parameters:
message (str)