Coverage for ase/calculators/calculator.py: 83.98%
543 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1import copy
2import os
3import shlex
4import subprocess
5import warnings
6from abc import abstractmethod
7from collections.abc import Sequence
8from dataclasses import dataclass, field
9from math import pi, sqrt
10from pathlib import Path
11from typing import Any
13import numpy as np
15from ase.calculators.abc import GetPropertiesMixin
16from ase.cell import Cell
17from ase.config import cfg as _cfg
18from ase.outputs import Properties, all_outputs
19from ase.utils import deprecated, jsonable
21from .names import names
24class CalculatorError(RuntimeError):
25 """Base class of error types related to ASE calculators."""
28class CalculatorSetupError(CalculatorError):
29 """Calculation cannot be performed with the given parameters.
31 Reasons to raise this error are:
32 * The calculator is not properly configured
33 (missing executable, environment variables, ...)
34 * The given atoms object is not supported
35 * Calculator parameters are unsupported
37 Typically raised before a calculation."""
40class EnvironmentError(CalculatorSetupError):
41 """Raised if calculator is not properly set up with ASE.
43 May be missing an executable or environment variables."""
46class InputError(CalculatorSetupError):
47 """Raised if inputs given to the calculator were incorrect.
49 Bad input keywords or values, or missing pseudopotentials.
51 This may be raised before or during calculation, depending on
52 when the problem is detected."""
55class CalculationFailed(CalculatorError):
56 """Calculation failed unexpectedly.
58 Reasons to raise this error are:
59 * Calculation did not converge
60 * Calculation ran out of memory
61 * Segmentation fault or other abnormal termination
62 * Arithmetic trouble (singular matrices, NaN, ...)
64 Typically raised during calculation."""
67class SCFError(CalculationFailed):
68 """SCF loop did not converge."""
71class ReadError(CalculatorError):
72 """Unexpected irrecoverable error while reading calculation results."""
75class PropertyNotImplementedError(NotImplementedError):
76 """Raised if a calculator does not implement the requested property."""
79class PropertyNotPresent(CalculatorError):
80 """Requested property is missing.
82 Maybe it was never calculated, or for some reason was not extracted
83 with the rest of the results, without being a fatal ReadError."""
86def compare_atoms(atoms1, atoms2, tol=1e-15, excluded_properties=None):
87 """Check for system changes since last calculation. Properties in
88 ``excluded_properties`` are not checked."""
89 if atoms1 is None:
90 system_changes = all_changes[:]
91 else:
92 system_changes = []
94 properties_to_check = set(all_changes)
95 if excluded_properties:
96 properties_to_check -= set(excluded_properties)
98 # Check properties that aren't in Atoms.arrays but are attributes of
99 # Atoms objects
100 for prop in ['cell', 'pbc']:
101 if prop in properties_to_check:
102 properties_to_check.remove(prop)
103 if not equal(
104 getattr(atoms1, prop), getattr(atoms2, prop), atol=tol
105 ):
106 system_changes.append(prop)
108 arrays1 = set(atoms1.arrays)
109 arrays2 = set(atoms2.arrays)
111 # Add any properties that are only in atoms1.arrays or only in
112 # atoms2.arrays (and aren't excluded). Note that if, e.g. arrays1 has
113 # `initial_charges` which is merely zeros and arrays2 does not have
114 # this array, we'll still assume that the system has changed. However,
115 # this should only occur rarely.
116 system_changes += properties_to_check & (arrays1 ^ arrays2)
118 # Finally, check all of the non-excluded properties shared by the atoms
119 # arrays.
120 for prop in properties_to_check & arrays1 & arrays2:
121 if not equal(atoms1.arrays[prop], atoms2.arrays[prop], atol=tol):
122 system_changes.append(prop)
124 return system_changes
127all_properties = [
128 'energy',
129 'forces',
130 'stress',
131 'stresses',
132 'dipole',
133 'charges',
134 'magmom',
135 'magmoms',
136 'free_energy',
137 'energies',
138 'dielectric_tensor',
139 'born_effective_charges',
140 'polarization',
141]
144all_changes = [
145 'positions',
146 'numbers',
147 'cell',
148 'pbc',
149 'initial_charges',
150 'initial_magmoms',
151]
154special = {
155 'cp2k': 'CP2K',
156 'demonnano': 'DemonNano',
157 'dftd3': 'DFTD3',
158 'dmol': 'DMol3',
159 'eam': 'EAM',
160 'elk': 'ELK',
161 'emt': 'EMT',
162 'exciting': 'ExcitingGroundStateCalculator',
163 'crystal': 'CRYSTAL',
164 'ff': 'ForceField',
165 'gamess_us': 'GAMESSUS',
166 'gulp': 'GULP',
167 'kim': 'KIM',
168 'lammpsrun': 'LAMMPS',
169 'lammpslib': 'LAMMPSlib',
170 'lj': 'LennardJones',
171 'mopac': 'MOPAC',
172 'morse': 'MorsePotential',
173 'nwchem': 'NWChem',
174 'openmx': 'OpenMX',
175 'orca': 'ORCA',
176 'qchem': 'QChem',
177 'tip3p': 'TIP3P',
178 'tip4p': 'TIP4P',
179}
182external_calculators: dict[str, type] = {}
185def register_calculator_class(name, cls):
186 """Add the class into the database."""
187 assert name not in external_calculators
188 external_calculators[name] = cls
189 names.append(name)
190 names.sort()
193def get_calculator_class(name):
194 """Return calculator class."""
195 if name == 'asap':
196 from asap3 import EMT as Calculator
197 elif name == 'gpaw':
198 from gpaw import GPAW as Calculator
199 elif name == 'hotbit':
200 from hotbit import Calculator
201 elif name == 'vasp':
202 from ase.calculators.vasp import Vasp as Calculator
203 elif name == 'ace':
204 from ase.calculators.acemolecule import ACE as Calculator
205 elif name == 'Psi4':
206 from ase.calculators.psi4 import Psi4 as Calculator
207 elif name == 'mattersim':
208 from mattersim.forcefield import MatterSimCalculator as Calculator
209 elif name == 'mace_mp':
210 from mace.calculators import mace_mp as Calculator
211 elif name in external_calculators:
212 Calculator = external_calculators[name]
213 else:
214 classname = special.get(name, name.title())
215 module = __import__('ase.calculators.' + name, {}, None, [classname])
216 Calculator = getattr(module, classname)
217 return Calculator
220def equal(a, b, tol=None, rtol=None, atol=None):
221 """ndarray-enabled comparison function."""
222 # XXX Known bugs:
223 # * Comparing cell objects (pbc not part of array representation)
224 # * Infinite recursion for cyclic dicts
225 # * Can of worms is open
226 if tol is not None:
227 msg = 'Use `equal(a, b, rtol=..., atol=...)` instead of `tol=...`'
228 warnings.warn(msg, DeprecationWarning)
229 assert rtol is None and atol is None, (
230 'Do not use deprecated `tol` with `atol` and/or `rtol`'
231 )
232 rtol = tol
233 atol = tol
235 a_is_dict = isinstance(a, dict)
236 b_is_dict = isinstance(b, dict)
237 if a_is_dict or b_is_dict:
238 # Check that both a and b are dicts
239 if not (a_is_dict and b_is_dict):
240 return False
241 if a.keys() != b.keys():
242 return False
243 return all(equal(a[key], b[key], rtol=rtol, atol=atol) for key in a)
245 if np.shape(a) != np.shape(b):
246 return False
248 if rtol is None and atol is None:
249 return np.array_equal(a, b)
251 if rtol is None:
252 rtol = 0
253 if atol is None:
254 atol = 0
256 return np.allclose(a, b, rtol=rtol, atol=atol)
259def kptdensity2monkhorstpack(atoms, kptdensity=3.5, even=True):
260 """Convert k-point density to Monkhorst-Pack grid size.
262 atoms: Atoms object
263 Contains unit cell and information about boundary conditions.
264 kptdensity: float
265 Required k-point density. Default value is 3.5 point per Ang^-1.
266 even: bool
267 Round up to even numbers.
268 """
270 recipcell = atoms.cell.reciprocal()
271 kpts = []
272 for i in range(3):
273 if atoms.pbc[i]:
274 k = 2 * pi * sqrt((recipcell[i] ** 2).sum()) * kptdensity
275 if even:
276 kpts.append(2 * int(np.ceil(k / 2)))
277 else:
278 kpts.append(int(np.ceil(k)))
279 else:
280 kpts.append(1)
281 return np.array(kpts)
284def kpts2mp(atoms, kpts, even=False):
285 if kpts is None:
286 return np.array([1, 1, 1])
287 if isinstance(kpts, (float, int)):
288 return kptdensity2monkhorstpack(atoms, kpts, even)
289 else:
290 return kpts
293def kpts2sizeandoffsets(
294 size=None, density=None, gamma=None, even=None, atoms=None
295):
296 """Helper function for selecting k-points.
298 Use either size or density.
300 size: 3 ints
301 Number of k-points.
302 density: float
303 K-point density in units of k-points per Ang^-1.
304 gamma: None or bool
305 Should the Gamma-point be included? Yes / no / don't care:
306 True / False / None.
307 even: None or bool
308 Should the number of k-points be even? Yes / no / don't care:
309 True / False / None.
310 atoms: Atoms object
311 Needed for calculating k-point density.
313 """
315 if size is not None and density is not None:
316 raise ValueError(
317 'Cannot specify k-point mesh size and density simultaneously'
318 )
319 elif density is not None and atoms is None:
320 raise ValueError(
321 'Cannot set k-points from "density" unless '
322 'Atoms are provided (need BZ dimensions).'
323 )
325 if size is None:
326 if density is None:
327 size = [1, 1, 1]
328 else:
329 size = kptdensity2monkhorstpack(atoms, density, None)
331 # Not using the rounding from kptdensity2monkhorstpack as it doesn't do
332 # rounding to odd numbers
333 if even is not None:
334 size = np.array(size)
335 remainder = size % 2
336 if even:
337 size += remainder
338 else: # Round up to odd numbers
339 size += 1 - remainder
341 offsets = [0, 0, 0]
342 if atoms is None:
343 pbc = [True, True, True]
344 else:
345 pbc = atoms.pbc
347 if gamma is not None:
348 for i, s in enumerate(size):
349 if pbc[i] and s % 2 != bool(gamma):
350 offsets[i] = 0.5 / s
352 return size, offsets
355@jsonable('kpoints')
356class KPoints:
357 def __init__(self, kpts=None):
358 if kpts is None:
359 kpts = np.zeros((1, 3))
360 self.kpts = kpts
362 def todict(self):
363 return vars(self)
366def kpts2kpts(kpts, atoms=None):
367 from ase.dft.kpoints import monkhorst_pack
369 if kpts is None:
370 return KPoints()
372 if hasattr(kpts, 'kpts'):
373 return kpts
375 if isinstance(kpts, dict):
376 if 'kpts' in kpts:
377 return KPoints(kpts['kpts'])
378 if 'path' in kpts:
379 cell = Cell.ascell(atoms.cell)
380 return cell.bandpath(pbc=atoms.pbc, **kpts)
381 size, offsets = kpts2sizeandoffsets(atoms=atoms, **kpts)
382 return KPoints(monkhorst_pack(size) + offsets)
384 if isinstance(kpts[0], int):
385 return KPoints(monkhorst_pack(kpts))
387 return KPoints(np.array(kpts))
390def kpts2ndarray(kpts, atoms=None):
391 """Convert kpts keyword to 2-d ndarray of scaled k-points."""
392 return kpts2kpts(kpts, atoms=atoms).kpts
395class Parameters(dict):
396 """Dictionary for parameters.
398 Special feature: If param is a Parameters instance, then param.xc
399 is a shorthand for param['xc'].
400 """
402 def __getattr__(self, key):
403 if key not in self:
404 return dict.__getattribute__(self, key)
405 return self[key]
407 def __setattr__(self, key, value):
408 self[key] = value
410 @classmethod
411 def read(cls, filename):
412 """Read parameters from file."""
413 # We use ast to evaluate literals, avoiding eval()
414 # for security reasons.
415 import ast
417 with open(filename) as fd:
418 txt = fd.read().strip()
419 assert txt.startswith('dict(')
420 assert txt.endswith(')')
421 txt = txt[5:-1]
423 # The tostring() representation "dict(...)" is not actually
424 # a literal, so we manually parse that along with the other
425 # formatting that we did manually:
426 dct = {}
427 for line in txt.splitlines():
428 key, val = line.split('=', 1)
429 key = key.strip()
430 val = val.strip()
431 if val[-1] == ',':
432 val = val[:-1]
433 dct[key] = ast.literal_eval(val)
435 parameters = cls(dct)
436 return parameters
438 def tostring(self):
439 keys = sorted(self)
440 return (
441 'dict('
442 + ',\n '.join(f'{key}={self[key]!r}' for key in keys)
443 + ')\n'
444 )
446 def write(self, filename):
447 Path(filename).write_text(self.tostring())
450class BaseCalculator(GetPropertiesMixin):
451 implemented_properties: list[str] = []
452 'Properties calculator can handle (energy, forces, ...)'
454 # Placeholder object for deprecated arguments. Let deprecated keywords
455 # default to _deprecated and then issue a warning if the user passed
456 # any other object (such as None).
457 _deprecated = object()
459 def __init__(self, parameters=None, use_cache=True):
460 if parameters is None:
461 parameters = {}
463 self.parameters = dict(parameters)
464 self.atoms = None
465 self.results = {}
466 self.use_cache = use_cache
468 def calculate_properties(self, atoms, properties):
469 """This method is experimental; currently for internal use."""
470 for name in properties:
471 if name not in all_outputs:
472 raise ValueError(f'No such property: {name}')
474 # We ignore system changes for now.
475 self.calculate(atoms, properties, system_changes=all_changes)
477 props = self.export_properties()
479 for name in properties:
480 if name not in props:
481 raise PropertyNotPresent(name)
482 return props
484 @abstractmethod
485 def calculate(self, atoms, properties, system_changes): ...
487 def check_state(self, atoms, tol=1e-15):
488 """Check for any system changes since last calculation."""
489 if self.use_cache:
490 return compare_atoms(self.atoms, atoms, tol=tol)
491 else:
492 return all_changes
494 def get_property(self, name, atoms=None, allow_calculation=True):
495 if name not in self.implemented_properties:
496 raise PropertyNotImplementedError(
497 f'{name} property not implemented'
498 )
500 if atoms is None:
501 atoms = self.atoms
502 system_changes = []
503 else:
504 system_changes = self.check_state(atoms)
506 if system_changes:
507 self.atoms = None
508 self.results = {}
510 if name not in self.results:
511 if not allow_calculation:
512 return None
514 if self.use_cache:
515 self.atoms = atoms.copy()
517 self.calculate(atoms, [name], system_changes)
519 if name not in self.results:
520 # For some reason the calculator was not able to do what we want,
521 # and that is OK.
522 raise PropertyNotImplementedError(
523 '{} not present in this calculation'.format(name)
524 )
526 result = self.results[name]
527 if isinstance(result, np.ndarray):
528 result = result.copy()
529 return result
531 def calculation_required(self, atoms, properties):
532 assert not isinstance(properties, str)
533 system_changes = self.check_state(atoms)
534 if system_changes:
535 return True
536 for name in properties:
537 if name not in self.results:
538 return True
539 return False
541 def export_properties(self):
542 return Properties(self.results)
544 def _get_name(self) -> str: # child class can override this
545 return self.__class__.__name__.lower()
547 @property
548 def name(self) -> str:
549 return self._get_name()
551 def todict(self) -> dict[str, Any]:
552 """Obtain a dictionary of parameter information"""
553 return {}
556class Calculator(BaseCalculator):
557 """Base-class for all ASE calculators.
559 A calculator must raise PropertyNotImplementedError if asked for a
560 property that it can't calculate. So, if calculation of the
561 stress tensor has not been implemented, get_stress(atoms) should
562 raise PropertyNotImplementedError. This can be achieved simply by not
563 including the string 'stress' in the list implemented_properties
564 which is a class member. These are the names of the standard
565 properties: 'energy', 'forces', 'stress', 'dipole', 'charges',
566 'magmom' and 'magmoms'.
567 """
569 default_parameters: dict[str, Any] = {}
570 'Default parameters'
572 ignored_changes: set[str] = set()
573 'Properties of Atoms which we ignore for the purposes of cache '
574 'invalidation with check_state().'
576 discard_results_on_any_change = False
577 'Whether we purge the results following any change in the set() method. '
578 'Most (file I/O) calculators will probably want this.'
580 def __init__(
581 self,
582 restart=None,
583 ignore_bad_restart_file=BaseCalculator._deprecated,
584 label=None,
585 atoms=None,
586 directory='.',
587 **kwargs,
588 ):
589 """Basic calculator implementation.
591 restart: str
592 Prefix for restart file. May contain a directory. Default
593 is None: don't restart.
594 ignore_bad_restart_file: bool
595 Deprecated, please do not use.
596 Passing more than one positional argument to Calculator()
597 is deprecated and will stop working in the future.
598 Ignore broken or missing restart file. By default, it is an
599 error if the restart file is missing or broken.
600 directory: str or PurePath
601 Working directory in which to read and write files and
602 perform calculations.
603 label: str
604 Name used for all files. Not supported by all calculators.
605 May contain a directory, but please use the directory parameter
606 for that instead.
607 atoms: Atoms object
608 Optional Atoms object to which the calculator will be
609 attached. When restarting, atoms will get its positions and
610 unit-cell updated from file.
611 """
612 self.atoms = None # copy of atoms object from last calculation
613 self.results = {} # calculated properties (energy, forces, ...)
614 self.parameters = None # calculational parameters
615 self._directory = None # Initialize
617 if ignore_bad_restart_file is self._deprecated:
618 ignore_bad_restart_file = False
619 else:
620 warnings.warn(
621 FutureWarning(
622 'The keyword "ignore_bad_restart_file" is deprecated and '
623 'will be removed in a future version of ASE. Passing more '
624 'than one positional argument to Calculator is also '
625 'deprecated and will stop functioning in the future. '
626 'Please pass arguments by keyword (key=value) except '
627 'optionally the "restart" keyword.'
628 )
629 )
631 if restart is not None:
632 try:
633 self.read(restart) # read parameters, atoms and results
634 except ReadError:
635 if ignore_bad_restart_file:
636 self.reset()
637 else:
638 raise
640 self.directory = directory
641 self.prefix = None
642 if label is not None:
643 if self.directory == '.' and '/' in label:
644 # We specified directory in label, and nothing in the diretory
645 # key
646 self.label = label
647 elif '/' not in label:
648 # We specified our directory in the directory keyword
649 # or not at all
650 self.label = '/'.join((self.directory, label))
651 else:
652 raise ValueError(
653 'Directory redundantly specified though '
654 'directory="{}" and label="{}". '
655 'Please omit "/" in label.'.format(self.directory, label)
656 )
658 if self.parameters is None:
659 # Use default parameters if they were not read from file:
660 self.parameters = self.get_default_parameters()
662 if atoms is not None:
663 atoms.calc = self
664 if self.atoms is not None:
665 # Atoms were read from file. Update atoms:
666 if not (
667 equal(atoms.numbers, self.atoms.numbers)
668 and (atoms.pbc == self.atoms.pbc).all()
669 ):
670 raise CalculatorError('Atoms not compatible with file')
671 atoms.positions = self.atoms.positions
672 atoms.cell = self.atoms.cell
674 self.set(**kwargs)
676 if not hasattr(self, 'get_spin_polarized'):
677 self.get_spin_polarized = self._deprecated_get_spin_polarized
678 # XXX We are very naughty and do not call super constructor!
680 # For historical reasons we have a particular caching protocol.
681 # We disable the superclass' optional cache.
682 self.use_cache = False
684 @property
685 def directory(self) -> str:
686 return self._directory
688 @directory.setter
689 def directory(self, directory: str | os.PathLike):
690 self._directory = str(Path(directory)) # Normalize path.
692 @property
693 def label(self):
694 if self.directory == '.':
695 return self.prefix
697 # Generally, label ~ directory/prefix
698 #
699 # We use '/' rather than os.pathsep because
700 # 1) directory/prefix does not represent any actual path
701 # 2) We want the same string to work the same on all platforms
702 if self.prefix is None:
703 return self.directory + '/'
705 return f'{self.directory}/{self.prefix}'
707 @label.setter
708 def label(self, label):
709 if label is None:
710 self.directory = '.'
711 self.prefix = None
712 return
714 tokens = label.rsplit('/', 1)
715 if len(tokens) == 2:
716 directory, prefix = tokens
717 else:
718 assert len(tokens) == 1
719 directory = '.'
720 prefix = tokens[0]
721 if prefix == '':
722 prefix = None
723 self.directory = directory
724 self.prefix = prefix
726 def set_label(self, label):
727 """Set label and convert label to directory and prefix.
729 Examples
730 --------
732 * label='abc': (directory='.', prefix='abc')
733 * label='dir1/abc': (directory='dir1', prefix='abc')
734 * label=None: (directory='.', prefix=None)
735 """
736 self.label = label
738 def get_default_parameters(self):
739 return Parameters(copy.deepcopy(self.default_parameters))
741 def todict(self, skip_default=True):
742 defaults = self.get_default_parameters()
743 dct = {}
744 for key, value in self.parameters.items():
745 if hasattr(value, 'todict'):
746 value = value.todict()
747 if skip_default:
748 default = defaults.get(key, '_no_default_')
749 if default != '_no_default_' and equal(value, default):
750 continue
751 dct[key] = value
752 return dct
754 def reset(self):
755 """Clear all information from old calculation."""
757 self.atoms = None
758 self.results = {}
760 def read(self, label):
761 """Read atoms, parameters and calculated properties from output file.
763 Read result from self.label file. Raise ReadError if the file
764 is not there. If the file is corrupted or contains an error
765 message from the calculation, a ReadError should also be
766 raised. In case of success, these attributes must set:
768 atoms: Atoms object
769 The state of the atoms from last calculation.
770 parameters: Parameters object
771 The parameter dictionary.
772 results: dict
773 Calculated properties like energy and forces.
775 The FileIOCalculator.read() method will typically read atoms
776 and parameters and get the results dict by calling the
777 read_results() method."""
779 self.set_label(label)
781 def get_atoms(self):
782 if self.atoms is None:
783 raise ValueError('Calculator has no atoms')
784 atoms = self.atoms.copy()
785 atoms.calc = self
786 return atoms
788 @classmethod
789 def read_atoms(cls, restart, **kwargs):
790 return cls(restart=restart, label=restart, **kwargs).get_atoms()
792 def set(self, **kwargs):
793 """Set parameters like set(key1=value1, key2=value2, ...).
795 A dictionary containing the parameters that have been changed
796 is returned.
798 Subclasses must implement a set() method that will look at the
799 chaneged parameters and decide if a call to reset() is needed.
800 If the changed parameters are harmless, like a change in
801 verbosity, then there is no need to call reset().
803 The special keyword 'parameters' can be used to read
804 parameters from a file."""
806 if 'parameters' in kwargs:
807 filename = kwargs.pop('parameters')
808 parameters = Parameters.read(filename)
809 parameters.update(kwargs)
810 kwargs = parameters
812 changed_parameters = {}
814 for key, value in kwargs.items():
815 oldvalue = self.parameters.get(key)
816 if key not in self.parameters or not equal(value, oldvalue):
817 changed_parameters[key] = value
818 self.parameters[key] = value
820 if self.discard_results_on_any_change and changed_parameters:
821 self.reset()
822 return changed_parameters
824 def check_state(self, atoms, tol=1e-15):
825 """Check for any system changes since last calculation."""
826 return compare_atoms(
827 self.atoms,
828 atoms,
829 tol=tol,
830 excluded_properties=set(self.ignored_changes),
831 )
833 def calculate(
834 self, atoms=None, properties=None, system_changes=all_changes
835 ):
836 """Do the calculation.
838 properties: list of str
839 List of what needs to be calculated. Can be any combination
840 of 'energy', 'forces', 'stress', 'dipole', 'charges', 'magmom'
841 and 'magmoms'.
842 system_changes: list of str
843 List of what has changed since last calculation. Can be
844 any combination of these six: 'positions', 'numbers', 'cell',
845 'pbc', 'initial_charges' and 'initial_magmoms'.
847 Subclasses need to implement this, but can ignore properties
848 and system_changes if they want. Calculated properties should
849 be inserted into results dictionary like shown in this dummy
850 example::
852 self.results = {'energy': 0.0,
853 'forces': np.zeros((len(atoms), 3)),
854 'stress': np.zeros(6),
855 'dipole': np.zeros(3),
856 'charges': np.zeros(len(atoms)),
857 'magmom': 0.0,
858 'magmoms': np.zeros(len(atoms))}
860 The subclass implementation should first call this
861 implementation to set the atoms attribute and create any missing
862 directories.
863 """
864 if properties is None:
865 properties = ['energy']
866 if atoms is not None:
867 self.atoms = atoms.copy()
868 if not os.path.isdir(self._directory):
869 try:
870 os.makedirs(self._directory)
871 except FileExistsError as e:
872 # We can only end up here in case of a race condition if
873 # multiple Calculators are running concurrently *and* use the
874 # same _directory, which cannot be expected to work anyway.
875 msg = (
876 'Concurrent use of directory '
877 + self._directory
878 + 'by multiple Calculator instances detected. Please '
879 'use one directory per instance.'
880 )
881 raise RuntimeError(msg) from e
883 @deprecated('Please use `ase.calculators.fd.FiniteDifferenceCalculator`.')
884 def calculate_numerical_forces(self, atoms, d=0.001):
885 """Calculate numerical forces using finite difference.
887 All atoms will be displaced by +d and -d in all directions.
889 .. deprecated:: 3.24.0
890 """
891 from ase.calculators.fd import calculate_numerical_forces
893 return calculate_numerical_forces(atoms, eps=d)
895 @deprecated('Please use `ase.calculators.fd.FiniteDifferenceCalculator`.')
896 def calculate_numerical_stress(self, atoms, d=1e-6, voigt=True):
897 """Calculate numerical stress using finite difference.
899 .. deprecated:: 3.24.0
900 """
901 from ase.calculators.fd import calculate_numerical_stress
903 return calculate_numerical_stress(atoms, eps=d, voigt=voigt)
905 def _deprecated_get_spin_polarized(self):
906 msg = (
907 'This calculator does not implement get_spin_polarized(). '
908 'In the future, calc.get_spin_polarized() will work only on '
909 'calculator classes that explicitly implement this method or '
910 'inherit the method via specialized subclasses.'
911 )
912 warnings.warn(msg, FutureWarning)
913 return False
915 def band_structure(self):
916 """Create band-structure object for plotting."""
917 from ase.spectrum.band_structure import get_band_structure
919 # XXX This calculator is supposed to just have done a band structure
920 # calculation, but the calculator may not have the correct Fermi level
921 # if it updated the Fermi level after changing k-points.
922 # This will be a problem with some calculators (currently GPAW), and
923 # the user would have to override this by providing the Fermi level
924 # from the selfconsistent calculation.
925 return get_band_structure(calc=self)
928class OldShellProfile:
929 def __init__(self, command):
930 self.command = command
931 self.configvars = {}
933 def execute(self, calc):
934 if self.command is None:
935 raise EnvironmentError(
936 'Please set ${} environment variable '.format(
937 'ASE_' + self.calc.upper() + '_COMMAND'
938 )
939 + 'or supply the command keyword'
940 )
941 command = self.command
942 if 'PREFIX' in command:
943 command = command.replace('PREFIX', calc.prefix)
945 try:
946 proc = subprocess.Popen(command, shell=True, cwd=calc.directory)
947 except OSError as err:
948 # Actually this may never happen with shell=True, since
949 # probably the shell launches successfully. But we soon want
950 # to allow calling the subprocess directly, and then this
951 # distinction (failed to launch vs failed to run) is useful.
952 msg = f'Failed to execute "{command}"'
953 raise EnvironmentError(msg) from err
955 errorcode = proc.wait()
957 if errorcode:
958 path = os.path.abspath(calc.directory)
959 msg = (
960 'Calculator "{}" failed with command "{}" failed in '
961 '{} with error code {}'.format(
962 calc.name, command, path, errorcode
963 )
964 )
965 raise CalculationFailed(msg)
968@dataclass
969class FileIORules:
970 """Rules for controlling streams options to external command.
972 FileIOCalculator will direct stdin and stdout and append arguments
973 to the calculator command using the specifications on this class.
975 Currently names can contain "{prefix}" which will be substituted by
976 calc.prefix. This will go away if/when we can remove prefix."""
978 extend_argv: Sequence[str] = tuple()
979 stdin_name: str | None = None
980 stdout_name: str | None = None
982 configspec: dict[str, Any] = field(default_factory=dict)
984 def load_config(self, section):
985 dct = {}
986 for key, value in self.configspec.items():
987 if key in section:
988 value = section[key]
989 dct[key] = value
990 return dct
993class BadConfiguration(Exception):
994 pass
997def _validate_command(command: str) -> str:
998 # We like to store commands as strings (and call shlex.split() later),
999 # but we also like to validate them early. This will error out if
1000 # command contains syntax problems and will also normalize e.g.
1001 # multiple spaces:
1002 try:
1003 return shlex.join(shlex.split(command))
1004 except ValueError as err:
1005 raise BadConfiguration('Cannot parse command string') from err
1008@dataclass
1009class StandardProfile:
1010 command: str
1011 configvars: dict[str, Any] = field(default_factory=dict)
1013 def __post_init__(self):
1014 self.command = _validate_command(self.command)
1016 def execute(self, calc):
1017 try:
1018 self._call(calc, subprocess.check_call)
1019 except subprocess.CalledProcessError as err:
1020 directory = Path(calc.directory).resolve()
1021 msg = (
1022 f'Calculator {calc.name} failed with args {err.args} '
1023 f'in directory {directory}'
1024 )
1025 raise CalculationFailed(msg) from err
1027 def execute_nonblocking(self, calc):
1028 return self._call(calc, subprocess.Popen)
1030 @property
1031 def _split_command(self):
1032 # XXX Unduplicate common stuff between StandardProfile and
1033 # that of GenericFileIO
1034 return shlex.split(self.command)
1036 def _call(self, calc, subprocess_function):
1037 from contextlib import ExitStack
1039 directory = Path(calc.directory).resolve()
1040 fileio_rules = calc.fileio_rules
1042 with ExitStack() as stack:
1044 def _maybe_open(name, mode):
1045 if name is None:
1046 return None
1048 name = name.format(prefix=calc.prefix)
1049 directory = Path(calc.directory)
1050 return stack.enter_context(open(directory / name, mode))
1052 stdout_fd = _maybe_open(fileio_rules.stdout_name, 'wb')
1053 stdin_fd = _maybe_open(fileio_rules.stdin_name, 'rb')
1055 argv = [*self._split_command, *fileio_rules.extend_argv]
1056 argv = [arg.format(prefix=calc.prefix) for arg in argv]
1057 return subprocess_function(
1058 argv, cwd=directory, stdout=stdout_fd, stdin=stdin_fd
1059 )
1062class FileIOCalculator(Calculator):
1063 """Base class for calculators that write/read input/output files."""
1065 # Static specification of rules for this calculator:
1066 fileio_rules: FileIORules | None = None
1068 # command: Optional[str] = None
1069 # 'Command used to start calculation'
1071 # Fallback command when nothing else is specified.
1072 # There will be no fallback in the future; it must be explicitly
1073 # configured.
1074 _legacy_default_command: str | None = None
1076 cfg = _cfg # Ensure easy access to config for subclasses
1078 @classmethod
1079 def ruleset(cls, *args, **kwargs):
1080 """Helper for subclasses to define FileIORules."""
1081 return FileIORules(*args, **kwargs)
1083 def __init__(
1084 self,
1085 restart=None,
1086 ignore_bad_restart_file=Calculator._deprecated,
1087 label=None,
1088 atoms=None,
1089 command=None,
1090 profile=None,
1091 **kwargs,
1092 ):
1093 """File-IO calculator.
1095 command: str
1096 Command used to start calculation.
1097 """
1099 super().__init__(
1100 restart, ignore_bad_restart_file, label, atoms, **kwargs
1101 )
1103 if profile is None:
1104 profile = self._initialize_profile(command)
1105 self.profile = profile
1107 @property
1108 def command(self):
1109 # XXX deprecate me
1110 #
1111 # This is for calculators that invoke Popen directly on
1112 # self.command instead of letting us (superclass) do it.
1113 return self.profile.command
1115 @command.setter
1116 def command(self, command):
1117 self.profile.command = command
1119 @classmethod
1120 def load_argv_profile(cls, cfg, section_name):
1121 # Helper method to load configuration.
1122 # This is used by the tests, do not rely on this as it will change.
1123 try:
1124 section = cfg.parser[section_name]
1125 except KeyError:
1126 raise BadConfiguration(f'No {section_name!r} section')
1128 if cls.fileio_rules is not None:
1129 configvars = cls.fileio_rules.load_config(section)
1130 else:
1131 configvars = {}
1133 try:
1134 command = section['command']
1135 except KeyError:
1136 raise BadConfiguration(
1137 f'No command field in {section_name!r} section'
1138 )
1140 return StandardProfile(command, configvars)
1142 def _initialize_profile(self, command):
1143 if command is None:
1144 name = 'ASE_' + self.name.upper() + '_COMMAND'
1145 command = self.cfg.get(name)
1147 if command is None and self.name in self.cfg.parser:
1148 return self.load_argv_profile(self.cfg, self.name)
1150 if command is None:
1151 # XXX issue a FutureWarning if this causes the command
1152 # to no longer be None
1153 command = self._legacy_default_command
1155 if command is None:
1156 raise EnvironmentError(
1157 f'No configuration of {self.name}. '
1158 f'Missing section [{self.name}] in configuration'
1159 )
1161 return OldShellProfile(command)
1163 def calculate(
1164 self, atoms=None, properties=None, system_changes=all_changes
1165 ):
1166 if properties is None:
1167 properties = ['energy']
1168 Calculator.calculate(self, atoms, properties, system_changes)
1169 self.write_input(self.atoms, properties, system_changes)
1170 self.execute()
1171 self.read_results()
1173 def execute(self):
1174 self.profile.execute(self)
1176 def write_input(self, atoms, properties=None, system_changes=None):
1177 """Write input file(s).
1179 Call this method first in subclasses so that directories are
1180 created automatically."""
1182 absdir = os.path.abspath(self.directory)
1183 if absdir != os.curdir and not os.path.isdir(self.directory):
1184 os.makedirs(self.directory)
1186 def read_results(self):
1187 """Read energy, forces, ... from output file(s)."""