"""ASE calculator facade for SPR-KKR.
The calculator stores persistent user/ASE defaults. Materialization of one
concrete calculation lives in :mod:`ase2sprkkr.sprkkr.calculation`; process
execution is delegated to the generic execution subsystem.
"""
from __future__ import annotations
import copy
import os
import subprocess
from pathlib import Path
from typing import Any, Dict, Optional, Union
from ase.calculators.calculator import (
BaseCalculator, CalculationFailed, PropertyNotImplementedError, all_changes,
)
from kkrunner.runs import RunState
import numpy as np
from ..common.file_utils import Directory
from ..common.misc import config_property, first_non_none
from ..configuration import config
from ..potentials.potentials import Potential
from .profile import SPRKKRProfile, resolve_sprkkr_profile
from .sprkkr_atoms import SPRKKRAtoms
[docs]
class SPRKKR(BaseCalculator):
"""ASE-facing calculator for SPR-KKR.
``SPRKKR`` is a mutable facade holding defaults shared by calculations:
structure/potential, input parameters, filename templates, working directory
and execution policy. Preparation snapshots run-specific configuration and
materializes the selected physical state into independent calculation files.
Selected ``Atoms`` and ``Potential`` objects are mutable physical working
state, not per-run snapshots. This applies both to calculator defaults and
explicitly supplied objects: preparation may promote or normalize the
structure, add automatic empty spheres, and synchronize the potential. Once
preparation finishes, the returned :class:`PreparedCalculation` owns its
concrete files and resources, so execution no longer depends on subsequent
changes to those physical objects.
A calculator instance is not intended to be prepared concurrently from
multiple threads because filename-template counters and physical
preprocessing are mutable state. Prepared runners themselves own independent
resources and may run concurrently.
"""
implemented_properties = ["energy"]
[docs]
def __init__(
self,
label=None,
directory=".",
atoms=None,
potential=None,
input_file=True,
output_file=True,
potential_file=True,
input_parameters=None,
options=None,
print_output=None,
mpi: Optional[bool] = None,
empty_spheres: Optional[Union[str, bool, Dict]] = None,
executable_suffix=None,
executable_dir: Optional[Union[str, bool]] = None,
profile=None,
executor=None,
project=None,
**kwargs,
):
if potential is not None and not isinstance(potential, (bool, str)):
if atoms is not None:
raise ValueError(
"You can not specify both atoms and potential. "
"If you specify one of them, the other will be generated from it."
)
atoms = potential.atoms
elif atoms is not None:
atoms = SPRKKRAtoms.promote_ase_atoms(atoms)
self._potential = None
self.atoms = atoms
self.potential = potential
super().__init__(use_cache=False)
if directory is False:
self._directory = directory
else:
self.directory = directory
self.atoms = atoms
self.potential = potential
self.input_file = input_file
self.output_file = output_file
self.potential_file = potential_file
self.input_parameters = input_parameters
if options or kwargs:
self.input_parameters.set(options, **kwargs, unknown="find")
self.print_output = print_output
self.empty_spheres = empty_spheres
self.profile = resolve_sprkkr_profile(profile).with_overrides(
mpi=mpi,
executable_dir=executable_dir,
executable_suffix=executable_suffix,
)
self.executor = executor
self.project = project
self.label = label
self._counter = 0
print_output = config_property("print_output", config.running.print_output)
empty_spheres = config_property("empty_spheres", config.running.empty_spheres)
@property
def input_parameters(self):
"""Default :class:`InputParameters` used for new calculations."""
if self._input_parameters is None:
self.input_parameters = "SCF"
return self._input_parameters
@input_parameters.setter
def input_parameters(self, value):
if value is not None:
value = InputParameters.create(value)
self._input_parameters = value
[docs]
def set(
self,
options: Union[Dict[str, Any], str, None] = None,
value=None,
*,
unknown="find",
**kwargs,
):
"""Set values on the calculator's persistent input-parameter defaults."""
if isinstance(options, str):
options = {options: value}
elif value is not None:
raise ValueError(
"If value argument is given to SPRKKR.set, the options argument have to be string name of the value"
)
if kwargs or options:
self.input_parameters.set(options, **kwargs, unknown=unknown)
[docs]
def get(self, name):
"""Return an input-parameter value by name or ``SECTION.NAME`` path."""
return self.input_parameters.get(name)
@property
def potential(self) -> Potential:
"""Potential associated with the calculator, generated lazily from atoms."""
if self._potential is None:
if self._atoms is None:
return None
self._potential = Potential.from_atoms(self._atoms)
return self._potential
@potential.setter
def potential(self, pot):
self._potential = pot
if pot is not None and not isinstance(pot, (bool, str)):
atoms = pot.atoms
if atoms is not None:
self._atoms = atoms
else:
pot._atoms = self._atoms
@property
def atoms(self) -> SPRKKRAtoms:
"""Structure associated with the calculator."""
if self._atoms is None:
if self._potential is None or isinstance(self._potential, bool):
return None
if isinstance(self._potential, str):
self._potential = Potential.from_file(self._potential)
self._atoms = self._potential.atoms
return self._atoms
@atoms.setter
def atoms(self, atoms):
atoms = SPRKKRAtoms.promote_ase_atoms(atoms)
self._atoms = atoms
if self._potential is not None and self._potential is not False:
if isinstance(self._potential, str):
self._potential = None
elif self._potential is not True:
self._potential.atoms = atoms
@property
def directory(self):
"""Default working directory, or ``False`` for a temporary run directory."""
return self._directory
@directory.setter
def directory(self, directory: Union[bool, str, os.PathLike]):
if not isinstance(directory, bool):
directory = str(Path(directory))
self._directory = directory
[docs]
def _advance_counter(self):
"""Advance the filename-template counter used by the legacy templator."""
self._counter += 1
return str(self._counter)
[docs]
def prepare(
self,
atoms=None,
input_parameters=None,
potential=None,
input_file=None,
potential_file=None,
output_file=None,
directory: Union[str, bool, Directory, None] = None,
create_subdirs: bool = False,
options=None,
task=None,
empty_spheres=None,
allow_temporary_files: bool = True,
restart_scf: bool = False,
):
"""Materialize current calculation state into one prepared calculation.
``InputParameters`` are copied before one-shot task/options and generated
file values are applied. Selected ``Atoms`` and ``Potential`` objects are
not deep-copied and may be normalized or synchronized during preparation.
The returned :class:`PreparedCalculation` owns all concrete files and
temporary directory resources, so subsequent physical-state changes do
not alter the already materialized run. Call
:meth:`PreparedCalculation.close` when the object is not transferred to
a runner.
"""
prepared = PreparedCalculation.prepare(
default_atoms=self._atoms,
default_potential=self._potential,
default_input_parameters=self.input_parameters,
default_input_file=self.input_file,
default_potential_file=self.potential_file,
default_output_file=self.output_file,
default_directory=self._directory,
default_empty_spheres=self.empty_spheres,
label=self.label,
counter=self._counter,
atoms=atoms,
input_parameters=input_parameters,
potential=potential,
input_file=input_file,
potential_file=potential_file,
output_file=output_file,
directory=directory,
create_subdirs=create_subdirs,
options=options,
task=task,
empty_spheres=empty_spheres,
allow_temporary_files=allow_temporary_files,
restart_scf=restart_scf,
)
self._counter = prepared.counter
return prepared
[docs]
@staticmethod
def _is_temporary_directory(directory):
if directory is False:
return True
return isinstance(directory, Directory) and directory.dir is False
[docs]
def create_run(
self,
atoms=None,
input_parameters=None,
potential=None,
input_file=None,
potential_file=None,
output_file=None,
directory: Union[str, bool, Directory, None] = None,
create_subdirs: bool = False,
options=None,
task=None,
empty_spheres: Optional[str | bool] = None,
print_output=None,
read_callback: Optional[callable] = None,
callback=None,
gdb=False,
profile: Optional[SPRKKRProfile] = None,
executor=None,
project=None,
restart_scf: bool = False,
error_file=None,
metadata=None,
):
"""Prepare a calculation and return an unstarted owning runner.
An explicit per-run executor has highest precedence. Otherwise an
explicit per-run profile selects its backend; if neither is supplied,
the calculator-level executor (when present) overrides the calculator
profile backend.
``error_file=None`` stores stderr next to stdout as ``<output>.err``.
``error_file=True`` deliberately merges stderr into ``output_file``;
``False`` requests a managed temporary stderr file, and an explicit path
or file object stores stderr there instead.
``callback`` is a terminal runner callback. It can therefore be invoked
with a partially populated result when backend execution or parsing
fails. ``read_callback`` observes streamed stdout/stderr.
"""
explicit_profile = profile is not None
run_profile = resolve_sprkkr_profile(
self.profile if profile is None else profile
)
print_output = first_non_none(print_output, self.print_output)
if project is None:
project = self.project
if executor is None and not explicit_profile:
executor = self.executor
prepared = self.prepare(
atoms=atoms,
input_parameters=input_parameters,
potential=potential,
input_file=input_file,
potential_file=potential_file,
output_file=output_file,
directory=directory,
create_subdirs=create_subdirs,
empty_spheres=empty_spheres,
options=options,
task=task,
allow_temporary_files=True,
restart_scf=restart_scf,
)
return prepared.create_run(
result_context=self,
profile=run_profile,
executor=executor,
project=project,
print_output=print_output,
read_callback=read_callback,
callback=callback,
gdb=gdb,
error_file=error_file,
create_subdirs=create_subdirs,
metadata=metadata,
)
[docs]
def value_or_default(self, name, value):
"""Return calculator default *name* when *value* is ``None``."""
if value is None:
value = getattr(self, name)
return value
[docs]
def _update_from_result(self, result, *, adopt_potential=False):
"""Update calculator state from a completed synchronous result."""
if hasattr(result, "energy"):
self.results["energy"] = result.energy
if adopt_potential:
try:
potential = result.potential
except (ValueError, FileNotFoundError):
return
if potential is not None:
self.potential = potential
[docs]
def calculate(
self,
atoms=None,
properties=("energy",),
system_changes=all_changes,
input_parameters=None,
potential=None,
input_file=None,
potential_file=None,
output_file=None,
directory: Union[str, bool, Directory, None] = None,
create_subdirs: bool = False,
empty_spheres: Optional[str | bool] = None,
mpi: bool = None,
options=None,
task=None,
print_output=None,
read_callback: Optional[callable] = None,
executable_suffix=None,
callback=None,
executable_dir=None,
gdb=False,
profile=None,
executor=None,
project=None,
restart_scf: bool = False,
error_file=None,
metadata=None,
):
"""Run one SPR-KKR task synchronously and return its parsed result.
``properties`` and ``system_changes`` are accepted for ASE compatibility.
SPR-KKR execution is task-oriented, so ``properties`` does not select a
different backend task and ``system_changes`` is not used for incremental
updates; each run materializes the complete supplied calculation state.
Per-call ``mpi``, ``executable_dir`` and ``executable_suffix`` values are
immutable overrides of the selected execution profile.
The callback of this synchronous convenience method is intentionally a
success callback: it runs only after the result has updated calculator
state. This differs from the lower-level terminal callback accepted by
:meth:`create_run`. An unsuccessful execution raises ASE's
:class:`CalculationFailed` before updating calculator state.
"""
if executor is None and profile is None:
executor = self.executor
run_profile = resolve_sprkkr_profile(
self.profile if profile is None else profile
).with_overrides(
mpi=mpi,
executable_dir=executable_dir,
executable_suffix=executable_suffix,
)
runner = self.create_run(
atoms=atoms,
input_parameters=input_parameters,
potential=potential,
input_file=input_file,
potential_file=potential_file,
output_file=output_file,
directory=directory,
create_subdirs=create_subdirs,
options=options,
task=task,
empty_spheres=empty_spheres,
print_output=print_output,
read_callback=read_callback,
gdb=gdb,
profile=run_profile,
executor=executor,
project=project,
restart_scf=restart_scf,
error_file=error_file,
metadata=metadata,
)
result = runner.run()
if runner.state != RunState.FINISHED:
raise CalculationFailed(
f"SPR-KKR calculation {runner.state.value} "
f"(return code {runner.return_code}): {runner.failure_message}"
)
self._update_from_result(
result,
adopt_potential=(
result.task_name.upper() == "SCF"
and potential is None
and atoms is None
),
)
if callback:
callback(result)
return result
[docs]
def get_property(self, name, atoms=None, allow_calculation=True):
if name not in self.implemented_properties:
raise PropertyNotImplementedError(
f"{name} property not implemented"
)
if not allow_calculation:
return None
self.results.clear()
result = self.calculate(
atoms=atoms,
properties=(name,),
system_changes=all_changes,
)
if atoms is not None and result.task_name.upper() == "SCF":
self._update_from_result(result, adopt_potential=True)
if name not in self.results:
raise PropertyNotImplementedError(
f"{name} not present in this calculation"
)
value = self.results[name]
return value.copy() if isinstance(value, np.ndarray) else value
[docs]
def scf(self, *args, **kwargs):
"""Run an SCF calculation."""
self.calculate(input_parameters="SCF", *args, **kwargs)
[docs]
def phagen(self, *args, **kwargs):
"""Run a PHAGEN calculation."""
self.calculate(input_parameters="PHAGEN", *args, **kwargs)
[docs]
def kkrgen(self, *args, **kwargs):
"""Run a KKRGEN calculation."""
self.calculate(input_parameters="KKRGEN", *args, **kwargs)
[docs]
def kkrspec(self, *args, **kwargs):
"""Run a KKRSPEC calculation."""
self.calculate(input_parameters="KKRSPEC", *args, **kwargs)
[docs]
def kkrch(self, *args, **kwargs):
"""Run a KKRCH calculation."""
self.calculate(input_parameters="KKRCH", *args, **kwargs)
[docs]
def run_xband(self, executable="xband"):
"""Start the external ``xband`` executable detached from calculator IO."""
subprocess.Popen(executable, stdout=subprocess.DEVNULL)
[docs]
def copy_with_potential(self, potential):
"""Return a shallow calculator copy using *potential*."""
out = copy.copy(self)
out.potential = potential
out.results = out.results.copy()
return out
@property
def potential_object(self):
"""Return the calculator potential as a :class:`Potential` object."""
if isinstance(self.potential, str):
self.potential = Potential.from_file(self.potential)
return self.potential
[docs]
def change_task(self, task, retain_values=False):
"""Change the persistent default input-parameter task."""
self.input_parameters.change_task(task, retain_values)
# Keep these imports below the calculator class. Importing InputParameters while
# sprkkr.configuration is still initializing creates a cycle through potentials;
# calculation also imports InputParameters, so it must be delayed for the same
# reason. Method bodies resolve these globals only when called, after module init.
from ..input_parameters.input_parameters import InputParameters # NOQA: E402
from .calculation import ( # NOQA: E402
FilenameTemplator as _FilenameTemplator,
PreparedCalculation,
)
[docs]
class FilenameTemplator(_FilenameTemplator):
"""Backward-compatible facade for the historical calculator-based API."""
[docs]
def __init__(self, calculator, task, symbols):
self.calculator = calculator
super().__init__(calculator.label, calculator._counter, task, symbols)
def __call__(self, template):
rendered = super().__call__(template)
self.calculator._counter = self.counter
return rendered
SPRKKR.InputParameters = InputParameters
SPRKKR.Potential = Potential