Coverage for ase/calculators/kim/calculators.py: 23.81%
84 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 os
2import re
4from ase.calculators.lammps import convert
5from ase.calculators.lammpslib import LAMMPSlib
6from ase.calculators.lammpsrun import LAMMPS
7from ase.data import atomic_masses, atomic_numbers
9from .exceptions import KIMCalculatorError
10from .kimmodel import KIMModelCalculator
13def KIMCalculator(model_name, options, debug):
14 """
15 Used only for Portable Models
16 """
18 options_not_allowed = ['modelname', 'debug']
20 _check_conflict_options(options, options_not_allowed, simulator='kimmodel')
22 return KIMModelCalculator(model_name, debug=debug, **options)
25def LAMMPSRunCalculator(
26 model_name, model_type, supported_species, options, debug, **kwargs
27):
28 """Used for Portable Models or LAMMPS Simulator Models if
29 specifically requested"""
31 def get_params(model_name, supported_units, supported_species, atom_style):
32 """
33 Extract parameters for LAMMPS calculator from model definition lines.
34 Returns a dictionary with entries for "pair_style" and "pair_coeff".
35 Expects there to be only one "pair_style" line. There can be multiple
36 "pair_coeff" lines (result is returned as a list).
37 """
38 parameters = {}
40 # In case the SM supplied its own atom_style in its model-init
41 # -- only needed because lammpsrun writes data files and needs
42 # to know the proper format
43 if atom_style:
44 parameters['atom_style'] = atom_style
46 # Set units to prevent them from defaulting to metal
47 parameters['units'] = supported_units
49 parameters['model_init'] = [
50 f'kim_init {model_name} {supported_units}{os.linesep}'
51 ]
53 parameters['kim_interactions'] = 'kim_interactions {}{}'.format(
54 (' ').join(supported_species), os.linesep
55 )
57 # For every species in "supported_species", add an entry to the
58 # "masses" key in dictionary "parameters".
59 parameters['masses'] = []
60 for i, species in enumerate(supported_species):
61 if species not in atomic_numbers:
62 raise KIMCalculatorError(
63 'Could not determine mass of unknown species '
64 '{} listed as supported by model'.format(species)
65 )
66 massstr = str(
67 convert(
68 atomic_masses[atomic_numbers[species]],
69 'mass',
70 'ASE',
71 supported_units,
72 )
73 )
74 parameters['masses'].append(str(i + 1) + ' ' + massstr)
76 return parameters
78 options_not_allowed = ['parameters', 'files', 'specorder', 'keep_tmp_files']
80 _check_conflict_options(options, options_not_allowed, simulator='lammpsrun')
82 # If no atom_style kwarg is passed, lammpsrun will default to
83 # atom_style atomic, which is what we want for KIM Portable Models
84 atom_style = kwargs.get('atom_style', None)
86 # Simulator Models will supply their own units from their
87 # metadata. For Portable Models, we use "metal" units.
88 supported_units = kwargs.get('supported_units', 'metal')
90 # Set up kim_init and kim_interactions lines
91 parameters = get_params(
92 model_name, supported_units, supported_species, atom_style
93 )
95 return LAMMPS(
96 **parameters,
97 specorder=supported_species,
98 keep_tmp_files=debug,
99 **options,
100 )
103def LAMMPSLibCalculator(
104 model_name, supported_species, supported_units, options
105):
106 """
107 Only used for LAMMPS Simulator Models
108 """
109 options_not_allowed = [
110 'lammps_header',
111 'lmpcmds',
112 'atom_types',
113 'log_file',
114 'keep_alive',
115 ]
117 _check_conflict_options(options, options_not_allowed, simulator='lammpslib')
118 # Set up LAMMPS header commands lookup table
120 # This units command actually has no effect, but is necessary because
121 # LAMMPSlib looks in the header lines for units in order to set them
122 # internally
123 model_init = ['units ' + supported_units + os.linesep]
125 model_init.append(f'kim_init {model_name} {supported_units}{os.linesep}')
126 model_init.append('atom_modify map array sort 0 0' + os.linesep)
128 # Assign atom types to species
129 atom_types = {s: i_s + 1 for i_s, s in enumerate(supported_species)}
130 kim_interactions = [
131 'kim_interactions {}'.format((' ').join(supported_species))
132 ]
134 # Return LAMMPSlib calculator
135 return LAMMPSlib(
136 lammps_header=model_init,
137 lammps_name=None,
138 lmpcmds=kim_interactions,
139 post_changebox_cmds=kim_interactions,
140 atom_types=atom_types,
141 log_file='lammps.log',
142 keep_alive=True,
143 **options,
144 )
147def ASAPCalculator(model_name, model_type, options, **kwargs):
148 """
149 Can be used with either Portable Models or Simulator Models
150 """
151 import asap3
153 options_not_allowed = {'pm': ['name', 'verbose'], 'sm': ['Params']}
155 _check_conflict_options(
156 options, options_not_allowed[model_type], simulator='asap'
157 )
159 if model_type == 'pm':
160 return asap3.OpenKIMcalculator(
161 name=model_name, verbose=kwargs['verbose'], **options
162 )
164 elif model_type == 'sm':
165 model_defn = kwargs['model_defn']
166 supported_units = kwargs['supported_units']
168 # Verify units (ASAP models are expected to work with "ase" units)
169 if supported_units != 'ase':
170 raise KIMCalculatorError(
171 'KIM Simulator Model units are "{}", but expected to '
172 'be "ase" for ASAP.'.format(supported_units)
173 )
175 # Check model_defn to make sure there's only one element in it
176 # that is a non-empty string
177 if len(model_defn) == 0:
178 raise KIMCalculatorError(
179 'model-defn is an empty list in metadata file of '
180 'Simulator Model {}'.format(model_name)
181 )
182 elif len(model_defn) > 1:
183 raise KIMCalculatorError(
184 'model-defn should contain only one entry for an ASAP '
185 'model (found {} lines)'.format(len(model_defn))
186 )
188 if '' in model_defn:
189 raise KIMCalculatorError(
190 'model-defn contains an empty string in metadata '
191 'file of Simulator '
192 'Model {}'.format(model_name)
193 )
195 model_defn = model_defn[0].strip()
197 # Instantiate calculator from ASAP. Currently, this must be one of:
198 # (1) EMT
199 # (2) EMT(EMTRasmussenParameters)
200 # (3) EMT(EMTMetalGlassParameters)
201 model_defn_is_valid = False
202 if model_defn.startswith('EMT'):
203 # Pull out potential parameters
204 mobj = re.search(r'\(([A-Za-z0-9_\(\)]+)\)', model_defn)
205 if mobj is None:
206 asap_calc = asap3.EMT()
207 else:
208 pp = mobj.group(1)
210 # Currently we only supported two specific EMT models
211 # that are built into ASAP
212 if pp.startswith('EMTRasmussenParameters'):
213 asap_calc = asap3.EMT(
214 parameters=asap3.EMTRasmussenParameters()
215 )
216 model_defn_is_valid = True
217 elif pp.startswith('EMTMetalGlassParameters'):
218 asap_calc = asap3.EMT(
219 parameters=asap3.EMTMetalGlassParameters()
220 )
221 model_defn_is_valid = True
223 if not model_defn_is_valid:
224 raise KIMCalculatorError(
225 'Unknown model "{}" requested for simulator asap.'.format(
226 model_defn
227 )
228 )
230 # Disable undocumented feature for the EMT self.calculators to
231 # take the energy of an isolated atoms as zero. (Otherwise it
232 # is taken to be that of perfect FCC.)
233 asap_calc.set_subtractE0(False)
235 return asap_calc
238def _check_conflict_options(options, options_not_allowed, simulator):
239 """Check whether options intended to be passed to a given calculator
240 are allowed. Some options are not allowed because they must be
241 set internally in this package."""
242 s1 = set(options)
243 s2 = set(options_not_allowed)
244 common = s1.intersection(s2)
246 if common:
247 options_in_not_allowed = ', '.join([f'"{s}"' for s in common])
249 msg = (
250 'Simulator "{}" does not support argument(s): '
251 '{} provided in "options", '
252 'because it is (they are) determined internally within the KIM '
253 'calculator'.format(simulator, options_in_not_allowed)
254 )
256 raise KIMCalculatorError(msg)