Coverage for ase/calculators/kim/kimpy_wrappers.py: 75.81%
339 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
1"""
2Wrappers that provide a minimal interface to kimpy methods and objects
4Daniel S. Karls
5University of Minnesota
6"""
8import functools
9from abc import ABC
11import numpy as np
13from .exceptions import (
14 KIMModelInitializationError,
15 KIMModelNotFound,
16 KIMModelParameterError,
17 KimpyError,
18)
21class LazyKimpyImport:
22 """This class avoids module level import of the optional kimpy module."""
24 def __getattr__(self, attr):
25 return getattr(self._kimpy, attr)
27 @functools.cached_property
28 def _kimpy(self):
29 import kimpy
31 return kimpy
34class Wrappers:
35 """Shortcuts written in a way that avoids module-level kimpy import."""
37 @property
38 def collections_create(self):
39 return functools.partial(check_call, kimpy.collections.create)
41 @property
42 def model_create(self):
43 return functools.partial(check_call, kimpy.model.create)
45 @property
46 def simulator_model_create(self):
47 return functools.partial(check_call, kimpy.simulator_model.create)
49 @property
50 def get_species_name(self):
51 return functools.partial(
52 check_call, kimpy.species_name.get_species_name
53 )
55 @property
56 def get_number_of_species_names(self):
57 return functools.partial(
58 check_call, kimpy.species_name.get_number_of_species_names
59 )
61 @property
62 def collection_item_type_portableModel(self):
63 return kimpy.collection_item_type.portableModel
66kimpy = LazyKimpyImport()
67wrappers = Wrappers()
69# Function used for casting parameter/extent indices to C-compatible ints
70c_int = np.intc
72# Function used for casting floating point parameter values to C-compatible
73# doubles
74c_double = np.double
77def c_int_args(func):
78 """
79 Decorator for instance methods that will cast all of the args passed,
80 excluding the first (which corresponds to 'self'), to C-compatible
81 integers.
82 """
84 @functools.wraps(func)
85 def myfunc(*args, **kwargs):
86 args_cast = [args[0]]
87 args_cast += map(c_int, args[1:])
88 return func(*args, **kwargs)
90 return myfunc
93def check_call(f, *args, **kwargs):
94 """Call a kimpy function using its arguments and, if a RuntimeError is
95 raised, catch it and raise a KimpyError with the exception's
96 message.
98 (Starting with kimpy 2.0.0, a RuntimeError is the only exception
99 type raised when something goes wrong.)"""
101 try:
102 return f(*args, **kwargs)
103 except RuntimeError as e:
104 raise KimpyError(
105 f'Calling kimpy function "{f.__name__}" failed:\n {e!s}'
106 )
109def check_call_wrapper(func):
110 @functools.wraps(func)
111 def myfunc(*args, **kwargs):
112 return check_call(func, *args, **kwargs)
114 return myfunc
117class ModelCollections:
118 """
119 KIM Portable Models and Simulator Models are installed/managed into
120 different "collections". In order to search through the different
121 KIM API model collections on the system, a corresponding object must
122 be instantiated. For more on model collections, see the KIM API's
123 install file:
124 https://github.com/openkim/kim-api/blob/master/INSTALL
125 """
127 def __init__(self):
128 self.collection = wrappers.collections_create()
130 def __enter__(self):
131 return self
133 def __exit__(self, exc_type, value, traceback):
134 pass
136 def get_item_type(self, model_name):
137 try:
138 model_type = check_call(self.collection.get_item_type, model_name)
139 except KimpyError:
140 msg = (
141 'Could not find model {} installed in any of the KIM API '
142 'model collections on this system. See '
143 'https://openkim.org/doc/usage/obtaining-models/ for '
144 'instructions on installing models.'.format(model_name)
145 )
146 raise KIMModelNotFound(msg)
148 return model_type
150 @property
151 def initialized(self):
152 return hasattr(self, 'collection')
155class PortableModel:
156 """Creates a KIM API Portable Model object and provides a minimal
157 interface to it"""
159 def __init__(self, model_name, debug):
160 self.model_name = model_name
161 self.debug = debug
163 # Create KIM API Model object
164 units_accepted, self.kim_model = wrappers.model_create(
165 kimpy.numbering.zeroBased,
166 kimpy.length_unit.A,
167 kimpy.energy_unit.eV,
168 kimpy.charge_unit.e,
169 kimpy.temperature_unit.K,
170 kimpy.time_unit.ps,
171 self.model_name,
172 )
174 if not units_accepted:
175 raise KIMModelInitializationError(
176 'Requested units not accepted in kimpy.model.create'
177 )
179 if self.debug:
180 l_unit, e_unit, c_unit, te_unit, ti_unit = check_call(
181 self.kim_model.get_units
182 )
183 print(f'Length unit is: {l_unit}')
184 print(f'Energy unit is: {e_unit}')
185 print(f'Charge unit is: {c_unit}')
186 print(f'Temperature unit is: {te_unit}')
187 print(f'Time unit is: {ti_unit}')
188 print()
190 self._create_parameters()
192 def __enter__(self):
193 return self
195 def __exit__(self, exc_type, value, traceback):
196 pass
198 @check_call_wrapper
199 def _get_number_of_parameters(self):
200 return self.kim_model.get_number_of_parameters()
202 def _create_parameters(self):
203 def _kim_model_parameter(**kwargs):
204 dtype = kwargs['dtype']
206 if dtype == 'Integer':
207 return KIMModelParameterInteger(**kwargs)
208 elif dtype == 'Double':
209 return KIMModelParameterDouble(**kwargs)
210 else:
211 raise KIMModelParameterError(
212 f'Invalid model parameter type {dtype}. Supported types '
213 "'Integer' and 'Double'."
214 )
216 self._parameters = {}
217 num_params = self._get_number_of_parameters()
218 for index_param in range(num_params):
219 parameter_metadata = self._get_one_parameter_metadata(index_param)
220 name = parameter_metadata['name']
222 self._parameters[name] = _kim_model_parameter(
223 kim_model=self.kim_model,
224 dtype=parameter_metadata['dtype'],
225 extent=parameter_metadata['extent'],
226 name=name,
227 description=parameter_metadata['description'],
228 parameter_index=index_param,
229 )
231 def get_model_supported_species_and_codes(self):
232 """Get all of the supported species for this model and their
233 corresponding integer codes that are defined in the KIM API
235 Returns
236 -------
237 species : list of str
238 Abbreviated chemical symbols of all species the mmodel
239 supports (e.g. ["Mo", "S"])
241 codes : list of int
242 Integer codes used by the model for each species (order
243 corresponds to the order of ``species``)
244 """
245 species = []
246 codes = []
247 num_kim_species = wrappers.get_number_of_species_names()
249 for i in range(num_kim_species):
250 species_name = wrappers.get_species_name(i)
252 species_is_supported, code = self.get_species_support_and_code(
253 species_name
254 )
256 if species_is_supported:
257 species.append(str(species_name))
258 codes.append(code)
260 return species, codes
262 @check_call_wrapper
263 def clear_then_refresh(self):
264 self.kim_model.clear_then_refresh()
266 @c_int_args
267 def _get_parameter_metadata(self, index_parameter):
268 try:
269 dtype, extent, name, description = check_call(
270 self.kim_model.get_parameter_metadata, index_parameter
271 )
272 except KimpyError as e:
273 raise KIMModelParameterError(
274 'Failed to retrieve metadata for '
275 f'parameter at index {index_parameter}'
276 ) from e
278 return dtype, extent, name, description
280 def parameters_metadata(self):
281 """Metadata associated with all model parameters.
283 Returns
284 -------
285 dict
286 Metadata associated with all model parameters.
287 """
288 return {
289 param_name: param.metadata
290 for param_name, param in self._parameters.items()
291 }
293 def parameter_names(self):
294 """Names of model parameters registered in the KIM API.
296 Returns
297 -------
298 tuple
299 Names of model parameters registered in the KIM API
300 """
301 return tuple(self._parameters.keys())
303 def get_parameters(self, **kwargs):
304 """
305 Get the values of one or more model parameter arrays.
307 Given the names of one or more model parameters and a set of indices
308 for each of them, retrieve the corresponding elements of the relevant
309 model parameter arrays.
311 Parameters
312 ----------
313 **kwargs
314 Names of the model parameters and the indices whose values should
315 be retrieved.
317 Returns
318 -------
319 dict
320 The requested indices and the values of the model's parameters.
322 Note
323 ----
324 The output of this method can be used as input of
325 ``set_parameters``.
327 Example
328 -------
329 To get `epsilons` and `sigmas` in the LJ universal model for Mo-Mo
330 (index 4879), Mo-S (index 2006) and S-S (index 1980) interactions::
332 >>> LJ = 'LJ_ElliottAkerson_2015_Universal__MO_959249795837_003'
333 >>> calc = KIM(LJ)
334 >>> calc.get_parameters(epsilons=[4879, 2006, 1980],
335 ... sigmas=[4879, 2006, 1980])
336 {'epsilons': [[4879, 2006, 1980],
337 [4.47499, 4.421814057295943, 4.36927]],
338 'sigmas': [[4879, 2006, 1980],
339 [2.74397, 2.30743, 1.87089]]}
340 """
341 parameters = {}
342 for parameter_name, index_range in kwargs.items():
343 parameters.update(
344 self._get_one_parameter(parameter_name, index_range)
345 )
346 return parameters
348 def set_parameters(self, **kwargs):
349 """
350 Set the values of one or more model parameter arrays.
352 Given the names of one or more model parameters and a set of indices
353 and corresponding values for each of them, mutate the corresponding
354 elements of the relevant model parameter arrays.
356 Parameters
357 ----------
358 **kwargs
359 Names of the model parameters to mutate and the corresponding
360 indices and values to set.
362 Returns
363 -------
364 dict
365 The requested indices and the values of the model's parameters
366 that were set.
368 Example
369 -------
370 To set `epsilons` in the LJ universal model for Mo-Mo (index 4879),
371 Mo-S (index 2006) and S-S (index 1980) interactions to 5.0, 4.5, and
372 4.0, respectively::
374 >>> LJ = 'LJ_ElliottAkerson_2015_Universal__MO_959249795837_003'
375 >>> calc = KIM(LJ)
376 >>> calc.set_parameters(epsilons=[[4879, 2006, 1980],
377 ... [5.0, 4.5, 4.0]])
378 {'epsilons': [[4879, 2006, 1980],
379 [5.0, 4.5, 4.0]]}
380 """
381 parameters = {}
382 for parameter_name, parameter_data in kwargs.items():
383 index_range, values = parameter_data
384 self._set_one_parameter(parameter_name, index_range, values)
385 parameters[parameter_name] = parameter_data
387 return parameters
389 def _get_one_parameter(self, parameter_name, index_range):
390 """
391 Retrieve value of one or more components of a model parameter array.
393 Parameters
394 ----------
395 parameter_name : str
396 Name of model parameter registered in the KIM API.
397 index_range : int or list
398 Zero-based index (int) or indices (list of int) specifying the
399 component(s) of the corresponding model parameter array that are
400 to be retrieved.
402 Returns
403 -------
404 dict
405 The requested indices and the corresponding values of the model
406 parameter array.
407 """
408 if parameter_name not in self._parameters:
409 raise KIMModelParameterError(
410 f"Parameter '{parameter_name}' is not "
411 'supported by this model. '
412 'Please check that the parameter name is spelled correctly.'
413 )
415 return self._parameters[parameter_name].get_values(index_range)
417 def _set_one_parameter(self, parameter_name, index_range, values):
418 """
419 Set the value of one or more components of a model parameter array.
421 Parameters
422 ----------
423 parameter_name : str
424 Name of model parameter registered in the KIM API.
425 index_range : int or list
426 Zero-based index (int) or indices (list of int) specifying the
427 component(s) of the corresponding model parameter array that are
428 to be mutated.
429 values : int/float or list
430 Value(s) to assign to the component(s) of the model parameter
431 array specified by ``index_range``.
432 """
433 if parameter_name not in self._parameters:
434 raise KIMModelParameterError(
435 f"Parameter '{parameter_name}' is not "
436 'supported by this model. '
437 'Please check that the parameter name is spelled correctly.'
438 )
440 self._parameters[parameter_name].set_values(index_range, values)
442 def _get_one_parameter_metadata(self, index_parameter):
443 """
444 Get metadata associated with a single model parameter.
446 Parameters
447 ----------
448 index_parameter : int
449 Zero-based index used by the KIM API to refer to this model
450 parameter.
452 Returns
453 -------
454 dict
455 Metadata associated with the requested model parameter.
456 """
457 dtype, extent, name, description = self._get_parameter_metadata(
458 index_parameter
459 )
460 parameter_metadata = {
461 'name': name,
462 'dtype': repr(dtype),
463 'extent': extent,
464 'description': description,
465 }
466 return parameter_metadata
468 @check_call_wrapper
469 def compute(self, compute_args_wrapped, release_GIL):
470 return self.kim_model.compute(
471 compute_args_wrapped.compute_args, release_GIL
472 )
474 @check_call_wrapper
475 def get_species_support_and_code(self, species_name):
476 return self.kim_model.get_species_support_and_code(species_name)
478 @check_call_wrapper
479 def get_influence_distance(self):
480 return self.kim_model.get_influence_distance()
482 @check_call_wrapper
483 def get_neighbor_list_cutoffs_and_hints(self):
484 return self.kim_model.get_neighbor_list_cutoffs_and_hints()
486 def compute_arguments_create(self):
487 return ComputeArguments(self, self.debug)
489 @property
490 def initialized(self):
491 return hasattr(self, 'kim_model')
494class KIMModelParameter(ABC):
495 def __init__(
496 self, kim_model, dtype, extent, name, description, parameter_index
497 ):
498 self._kim_model = kim_model
499 self._dtype = dtype
500 self._extent = extent
501 self._name = name
502 self._description = description
504 # Ensure that parameter_index is cast to a C-compatible integer. This
505 # is necessary because this is passed to kimpy.
506 self._parameter_index = c_int(parameter_index)
508 @property
509 def metadata(self):
510 return {
511 'dtype': self._dtype,
512 'extent': self._extent,
513 'name': self._name,
514 'description': self._description,
515 }
517 @c_int_args
518 def _get_one_value(self, index_extent):
519 get_parameter = getattr(self._kim_model, self._dtype_accessor)
520 try:
521 return check_call(
522 get_parameter, self._parameter_index, index_extent
523 )
524 except KimpyError as exception:
525 raise KIMModelParameterError(
526 f'Failed to access component {index_extent} of model '
527 f"parameter of type '{self._dtype}' at parameter index "
528 f'{self._parameter_index}'
529 ) from exception
531 def _set_one_value(self, index_extent, value):
532 value_typecast = self._dtype_c(value)
534 try:
535 check_call(
536 self._kim_model.set_parameter,
537 self._parameter_index,
538 c_int(index_extent),
539 value_typecast,
540 )
541 except KimpyError:
542 raise KIMModelParameterError(
543 f'Failed to set component {index_extent} at parameter index '
544 f'{self._parameter_index} to {self._dtype} value '
545 f'{value_typecast}'
546 )
548 def get_values(self, index_range):
549 index_range_dim = np.ndim(index_range)
550 if index_range_dim == 0:
551 values = self._get_one_value(index_range)
552 elif index_range_dim == 1:
553 values = []
554 for idx in index_range:
555 values.append(self._get_one_value(idx))
556 else:
557 raise KIMModelParameterError(
558 'Index range must be an integer or a list of integers'
559 )
560 return {self._name: [index_range, values]}
562 def set_values(self, index_range, values):
563 index_range_dim = np.ndim(index_range)
564 values_dim = np.ndim(values)
566 # Check the shape of index_range and values
567 msg = 'index_range and values must have the same shape'
568 assert index_range_dim == values_dim, msg
570 if index_range_dim == 0:
571 self._set_one_value(index_range, values)
572 elif index_range_dim == 1:
573 assert len(index_range) == len(values), msg
574 for idx, value in zip(index_range, values):
575 self._set_one_value(idx, value)
576 else:
577 raise KIMModelParameterError(
578 'Index range must be an integer or a list containing a '
579 'single integer'
580 )
583class KIMModelParameterInteger(KIMModelParameter):
584 _dtype_c = c_int
585 _dtype_accessor = 'get_parameter_int'
588class KIMModelParameterDouble(KIMModelParameter):
589 _dtype_c = c_double
590 _dtype_accessor = 'get_parameter_double'
593class ComputeArguments:
594 """Creates a KIM API ComputeArguments object from a KIM Portable
595 Model object and configures it for ASE. A ComputeArguments object
596 is associated with a KIM Portable Model and is used to inform the
597 KIM API of what the model can compute. It is also used to
598 register the data arrays that allow the KIM API to pass the atomic
599 coordinates to the model and retrieve the corresponding energy and
600 forces, etc."""
602 def __init__(self, kim_model_wrapped, debug):
603 self.kim_model_wrapped = kim_model_wrapped
604 self.debug = debug
606 # Create KIM API ComputeArguments object
607 self.compute_args = check_call(
608 self.kim_model_wrapped.kim_model.compute_arguments_create
609 )
611 # Check compute arguments
612 kimpy_arg_name = kimpy.compute_argument_name
613 num_arguments = kimpy_arg_name.get_number_of_compute_argument_names()
614 if self.debug:
615 print(f'Number of compute_args: {num_arguments}')
617 for i in range(num_arguments):
618 name = check_call(kimpy_arg_name.get_compute_argument_name, i)
619 dtype = check_call(
620 kimpy_arg_name.get_compute_argument_data_type, name
621 )
623 arg_support = self.get_argument_support_status(name)
625 if self.debug:
626 print(
627 'Compute Argument name {:21} is of type {:7} '
628 'and has support '
629 'status {}'.format(
630 *[str(x) for x in [name, dtype, arg_support]]
631 )
632 )
634 # See if the model demands that we ask it for anything
635 # other than energy and forces. If so, raise an
636 # exception.
637 if arg_support == kimpy.support_status.required:
638 if (
639 name != kimpy.compute_argument_name.partialEnergy
640 and name != kimpy.compute_argument_name.partialForces
641 ):
642 raise KIMModelInitializationError(
643 f'Unsupported required ComputeArgument {name}'
644 )
646 # Check compute callbacks
647 callback_name = kimpy.compute_callback_name
648 num_callbacks = callback_name.get_number_of_compute_callback_names()
649 if self.debug:
650 print()
651 print(f'Number of callbacks: {num_callbacks}')
653 for i in range(num_callbacks):
654 name = check_call(callback_name.get_compute_callback_name, i)
656 support_status = self.get_callback_support_status(name)
658 if self.debug:
659 print(
660 'Compute callback {:17} has support status {}'.format(
661 str(name), support_status
662 )
663 )
665 # Cannot handle any "required" callbacks
666 if support_status == kimpy.support_status.required:
667 raise KIMModelInitializationError(
668 f'Unsupported required ComputeCallback: {name}'
669 )
671 @check_call_wrapper
672 def set_argument_pointer(self, compute_arg_name, data_object):
673 return self.compute_args.set_argument_pointer(
674 compute_arg_name, data_object
675 )
677 @check_call_wrapper
678 def get_argument_support_status(self, name):
679 return self.compute_args.get_argument_support_status(name)
681 @check_call_wrapper
682 def get_callback_support_status(self, name):
683 return self.compute_args.get_callback_support_status(name)
685 @check_call_wrapper
686 def set_callback(
687 self, compute_callback_name, callback_function, data_object
688 ):
689 return self.compute_args.set_callback(
690 compute_callback_name, callback_function, data_object
691 )
693 @check_call_wrapper
694 def set_callback_pointer(
695 self, compute_callback_name, callback, data_object
696 ):
697 return self.compute_args.set_callback_pointer(
698 compute_callback_name, callback, data_object
699 )
701 def update(
702 self,
703 num_particles,
704 species_code,
705 particle_contributing,
706 coords,
707 energy,
708 forces,
709 ):
710 """Register model input and output in the kim_model object."""
711 compute_arg_name = kimpy.compute_argument_name
712 set_argument_pointer = self.set_argument_pointer
714 set_argument_pointer(compute_arg_name.numberOfParticles, num_particles)
715 set_argument_pointer(
716 compute_arg_name.particleSpeciesCodes, species_code
717 )
718 set_argument_pointer(
719 compute_arg_name.particleContributing, particle_contributing
720 )
721 set_argument_pointer(compute_arg_name.coordinates, coords)
722 set_argument_pointer(compute_arg_name.partialEnergy, energy)
723 set_argument_pointer(compute_arg_name.partialForces, forces)
725 if self.debug:
726 print('Debug: called update_kim')
727 print()
730class SimulatorModel:
731 """Creates a KIM API Simulator Model object and provides a minimal
732 interface to it. This is only necessary in this package in order to
733 extract any information about a given simulator model because it is
734 generally embedded in a shared object.
735 """
737 def __init__(self, model_name):
738 # Create a KIM API Simulator Model object for this model
739 self.model_name = model_name
740 self.simulator_model = wrappers.simulator_model_create(self.model_name)
742 # Need to close template map in order to access simulator
743 # model metadata
744 self.simulator_model.close_template_map()
746 def __enter__(self):
747 return self
749 def __exit__(self, exc_type, value, traceback):
750 pass
752 @property
753 def simulator_name(self):
754 simulator_name, _ = (
755 self.simulator_model.get_simulator_name_and_version()
756 )
757 return simulator_name
759 @property
760 def num_supported_species(self):
761 num_supported_species = (
762 self.simulator_model.get_number_of_supported_species()
763 )
764 if num_supported_species == 0:
765 raise KIMModelInitializationError(
766 'Unable to determine supported species of '
767 'simulator model {}.'.format(self.model_name)
768 )
769 return num_supported_species
771 @property
772 def supported_species(self):
773 supported_species = []
774 for spec_code in range(self.num_supported_species):
775 species = check_call(
776 self.simulator_model.get_supported_species, spec_code
777 )
778 supported_species.append(species)
780 return tuple(supported_species)
782 @property
783 def num_metadata_fields(self):
784 return self.simulator_model.get_number_of_simulator_fields()
786 @property
787 def metadata(self):
788 sm_metadata_fields = {}
789 for field in range(self.num_metadata_fields):
790 extent, field_name = check_call(
791 self.simulator_model.get_simulator_field_metadata, field
792 )
793 sm_metadata_fields[field_name] = []
794 for ln in range(extent):
795 field_line = check_call(
796 self.simulator_model.get_simulator_field_line, field, ln
797 )
798 sm_metadata_fields[field_name].append(field_line)
800 return sm_metadata_fields
802 @property
803 def supported_units(self):
804 try:
805 supported_units = self.metadata['units'][0]
806 except (KeyError, IndexError):
807 raise KIMModelInitializationError(
808 'Unable to determine supported units of '
809 'simulator model {}.'.format(self.model_name)
810 )
812 return supported_units
814 @property
815 def atom_style(self):
816 """
817 See if a 'model-init' field exists in the SM metadata and, if
818 so, whether it contains any entries including an "atom_style"
819 command. This is specific to LAMMPS SMs and is only required
820 for using the LAMMPSrun calculator because it uses
821 lammps.inputwriter to create a data file. All other content in
822 'model-init', if it exists, is ignored.
823 """
824 atom_style = None
825 for ln in self.metadata.get('model-init', []):
826 if ln.find('atom_style') != -1:
827 atom_style = ln.split()[1]
829 return atom_style
831 @property
832 def model_defn(self):
833 return self.metadata['model-defn']
835 @property
836 def initialized(self):
837 return hasattr(self, 'simulator_model')