Coverage for ase/calculators/kim/neighborlist.py: 52.38%
189 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
1from collections import defaultdict
3import numpy as np
5from ase import Atom
6from ase.neighborlist import neighbor_list
8from .kimpy_wrappers import c_double, c_int, check_call_wrapper, kimpy
11class NeighborList:
12 kimpy_arrays = {
13 'num_particles': c_int,
14 'coords': c_double,
15 'particle_contributing': c_int,
16 'species_code': c_int,
17 'cutoffs': c_double,
18 'padding_image_of': c_int,
19 'need_neigh': c_int,
20 }
22 def __setattr__(self, name, value):
23 """
24 Override assignment to any of the attributes listed in
25 kimpy_arrays to automatically cast the object to a numpy array.
26 This is done to avoid a ton of explicit numpy.array() calls (and
27 the possibility that we forget to do the cast). It is important
28 to use np.asarray() here instead of np.array() because using the
29 latter will mean that incrementation (+=) will create a new
30 object that the reference is bound to, which becomes a problem
31 if update_compute_args isn't called to reregister the
32 corresponding address with the KIM API.
33 """
34 if name in self.kimpy_arrays and value is not None:
35 value = np.asarray(value, dtype=self.kimpy_arrays[name])
36 self.__dict__[name] = value
38 def __init__(
39 self,
40 neigh_skin_ratio,
41 model_influence_dist,
42 model_cutoffs,
43 padding_not_require_neigh,
44 debug,
45 ):
47 self.set_neigh_parameters(
48 neigh_skin_ratio,
49 model_influence_dist,
50 model_cutoffs,
51 padding_not_require_neigh,
52 )
54 self.debug = debug
56 if self.debug:
57 print()
58 print(f'Calculator skin: {self.skin}')
59 print(f'Model influence distance: {model_influence_dist}')
60 print(
61 'Calculator influence distance (including skin distance): {}'
62 ''.format(self.influence_dist)
63 )
64 print(f'Number of cutoffs: {model_cutoffs.size}')
65 print(f'Model cutoffs: {model_cutoffs}')
66 print(
67 'Calculator cutoffs (including skin distance): {}'.format(
68 self.cutoffs
69 )
70 )
71 print(
72 'Model needs neighbors of padding atoms: {}'.format(
73 self.padding_need_neigh
74 )
75 )
76 print()
78 # Attributes to be set by subclasses
79 self.neigh = None
80 self.num_contributing_particles = None
81 self.padding_image_of = None
82 self.num_particles = None
83 self.coords = None
84 self.particle_contributing = None
85 self.species_code = None
86 self.need_neigh = None
87 self.last_update_positions = None
89 def set_neigh_parameters(
90 self,
91 neigh_skin_ratio,
92 model_influence_dist,
93 model_cutoffs,
94 padding_not_require_neigh,
95 ):
96 self.skin = neigh_skin_ratio * model_influence_dist
97 self.influence_dist = model_influence_dist + self.skin
98 self.cutoffs = model_cutoffs + self.skin
99 self.padding_need_neigh = not padding_not_require_neigh.all()
101 def update_kim_coords(self, atoms):
102 """Update atomic positions in self.coords, which is where the KIM
103 API will look to find them in order to pass them to the model.
104 """
105 if self.padding_image_of.size != 0:
106 disp_contrib = atoms.positions - self.coords[: len(atoms)]
107 disp_pad = disp_contrib[self.padding_image_of]
108 self.coords += np.concatenate((disp_contrib, disp_pad))
109 else:
110 np.copyto(self.coords, atoms.positions)
112 if self.debug:
113 print('Debug: called update_kim_coords')
114 print()
116 def need_neigh_update(self, atoms, system_changes):
117 need_neigh_update = True
118 if len(system_changes) == 1 and 'positions' in system_changes:
119 # Only position changes
120 if self.last_update_positions is not None:
121 a = self.last_update_positions
122 b = atoms.positions
123 if a.shape == b.shape:
124 delta = np.linalg.norm(a - b, axis=1)
125 # Indices of the two largest elements
126 try:
127 ind = np.argpartition(delta, -2)[-2:]
129 if sum(delta[ind]) <= self.skin:
130 need_neigh_update = False
131 except ValueError as error:
132 # if there is only a single atom that gets displaced
133 # np.argpartition(delta, -2) will fail with a
134 # ValueError, a single atom has no neighbors to update
135 if atoms.positions.shape[0] != 1:
136 raise error
137 need_neigh_update = False
139 return need_neigh_update
142class ASENeighborList(NeighborList):
143 def __init__(
144 self,
145 compute_args,
146 neigh_skin_ratio,
147 model_influence_dist,
148 model_cutoffs,
149 padding_not_require_neigh,
150 debug,
151 ):
152 super().__init__(
153 neigh_skin_ratio,
154 model_influence_dist,
155 model_cutoffs,
156 padding_not_require_neigh,
157 debug,
158 )
160 self.neigh = {}
161 compute_args.set_callback(
162 kimpy.compute_callback_name.GetNeighborList,
163 self.get_neigh,
164 self.neigh,
165 )
167 @staticmethod
168 def get_neigh(data, cutoffs, neighbor_list_index, particle_number):
169 """Retrieves the neighbors of each atom using ASE's native neighbor
170 list library
171 """
172 # We can only return neighbors of particles that were stored
173 number_of_particles = data['num_particles']
174 if particle_number >= number_of_particles or particle_number < 0:
175 return (np.array([]), 1)
177 neighbors = data['neighbors'][neighbor_list_index][particle_number]
178 return (neighbors, 0)
180 def build(self, orig_atoms):
181 """Build the ASE neighbor list and return an Atoms object with
182 all of the neighbors added. First a neighbor list is created
183 from ase.neighbor_list, having only information about the
184 neighbors of the original atoms. If neighbors of padding atoms
185 are required, they are calculated using information from the
186 first neighbor list.
187 """
188 syms = orig_atoms.get_chemical_symbols()
189 orig_num_atoms = len(orig_atoms)
190 orig_pos = orig_atoms.get_positions()
192 # New atoms object that will contain the contributing atoms plus
193 # the padding atoms
194 new_atoms = orig_atoms.copy()
196 neigh_list = defaultdict(list)
197 neigh_dists = defaultdict(list)
199 # Information for padding atoms
200 padding_image_of = []
201 padding_shifts = []
203 # Ask ASE to build the neighbor list using the influence distance.
204 # This is not a neighbor list for each atom, but rather a listing
205 # of all neighbor pairs that exist. Atoms with no neighbors will
206 # not show up.
207 (
208 neigh_indices_i,
209 neigh_indices_j,
210 relative_pos,
211 neigh_cell_offsets,
212 dists,
213 ) = neighbor_list('ijDSd', orig_atoms, self.influence_dist)
215 # Loop over all neighbor pairs. Because this loop will generally
216 # include image atoms (for periodic systems), we keep track of
217 # which atoms/images we've accounted for in the `used` dictionary.
218 used = {}
219 for neigh_i, neigh_j, rel_pos, offset, dist in zip(
220 neigh_indices_i,
221 neigh_indices_j,
222 relative_pos,
223 neigh_cell_offsets,
224 dists,
225 ):
226 # Get neighbor position of neighbor
227 # (mapped back into unit cell, so this may overlap with other atoms)
228 wrapped_pos = orig_pos[neigh_i] + rel_pos
230 shift = tuple(offset)
231 uniq_index = (neigh_j,) + shift
232 if shift == (0, 0, 0):
233 # This atom is in the unit cell, i.e. it is contributing
234 neigh_list[neigh_i].append(neigh_j)
235 neigh_dists[neigh_i].append(dist)
236 if uniq_index not in used:
237 used[uniq_index] = neigh_j
238 else:
239 # This atom is not in the unit cell, i.e. it is padding
240 if uniq_index not in used:
241 # Add the neighbor as a padding atom
242 used[uniq_index] = len(new_atoms)
243 new_atoms.append(Atom(syms[neigh_j], position=wrapped_pos))
244 padding_image_of.append(neigh_j)
245 padding_shifts.append(offset)
246 neigh_list[neigh_i].append(used[uniq_index])
247 neigh_dists[neigh_i].append(dist)
248 neighbor_list_size = orig_num_atoms
250 # Add neighbors of padding atoms if the potential requires them
251 if self.padding_need_neigh:
252 neighbor_list_size = len(new_atoms)
253 inv_used = {v: k for k, v in used.items()}
254 # Loop over all the neighbors (k) and the image of that neighbor
255 # in the cell (neigh)
256 for k, neigh in enumerate(padding_image_of):
257 # Shift from original atom in cell to neighbor
258 shift = padding_shifts[k]
259 for orig_neigh, orig_dist in zip(
260 neigh_list[neigh], neigh_dists[neigh]
261 ):
262 # Get the shift of the neighbor of the original atom
263 orig_shift = inv_used[orig_neigh][1:]
265 # Apply sum of original shift and current shift to
266 # neighbors of original atom
267 total_shift = orig_shift + shift
269 # Get the image in the cell of the original neighbor
270 if orig_neigh <= orig_num_atoms - 1:
271 orig_neigh_image = orig_neigh
272 else:
273 orig_neigh_image = padding_image_of[
274 orig_neigh - orig_num_atoms
275 ]
277 # If the original image with the total shift has been
278 # used before then it is also a neighbor of this atom
279 uniq_index = (orig_neigh_image,) + tuple(total_shift)
280 if uniq_index in used:
281 neigh_list[k + orig_num_atoms].append(used[uniq_index])
282 neigh_dists[k + orig_num_atoms].append(orig_dist)
284 # If the model has multiple cutoffs, we need to return neighbor lists
285 # corresponding to each of them
286 neigh_lists = []
287 for cut in self.cutoffs:
288 neigh_list = [
289 np.array(neigh_list[k], dtype=c_int)[neigh_dists[k] <= cut]
290 for k in range(neighbor_list_size)
291 ]
292 neigh_lists.append(neigh_list)
294 self.padding_image_of = padding_image_of
296 self.neigh['neighbors'] = neigh_lists
297 self.neigh['num_particles'] = neighbor_list_size
299 return new_atoms
301 def update(self, orig_atoms, species_map):
302 """Create the neighbor list along with the other required
303 parameters (which are stored as instance attributes). The
304 required parameters are:
306 - num_particles
307 - coords
308 - particle_contributing
309 - species_code
311 Note that the KIM API requires a neighbor list that has indices
312 corresponding to each atom.
313 """
315 # Information of original atoms
316 self.num_contributing_particles = len(orig_atoms)
318 new_atoms = self.build(orig_atoms)
320 # Save the number of atoms and all their neighbors and positions
321 num_atoms = len(new_atoms)
322 num_padding = num_atoms - self.num_contributing_particles
323 self.num_particles = [num_atoms]
324 self.coords = new_atoms.get_positions()
326 # Save which coordinates are from original atoms and which are from
327 # neighbors using a mask
328 indices_mask = [1] * self.num_contributing_particles + [0] * num_padding
329 self.particle_contributing = indices_mask
331 # Species support and code
332 try:
333 self.species_code = [
334 species_map[s] for s in new_atoms.get_chemical_symbols()
335 ]
336 except KeyError as e:
337 raise RuntimeError(
338 'Species not supported by KIM model; {}'.format(str(e))
339 )
341 self.last_update_positions = orig_atoms.get_positions()
343 if self.debug:
344 print('Debug: called update_ase_neigh')
345 print()
348class KimpyNeighborList(NeighborList):
349 def __init__(
350 self,
351 compute_args,
352 neigh_skin_ratio,
353 model_influence_dist,
354 model_cutoffs,
355 padding_not_require_neigh,
356 debug,
357 ):
358 super().__init__(
359 neigh_skin_ratio,
360 model_influence_dist,
361 model_cutoffs,
362 padding_not_require_neigh,
363 debug,
364 )
366 self.neigh = kimpy.neighlist.NeighList()
368 compute_args.set_callback_pointer(
369 kimpy.compute_callback_name.GetNeighborList,
370 kimpy.neighlist.get_neigh_kim(),
371 self.neigh,
372 )
374 @check_call_wrapper
375 def build(self):
376 return self.neigh.build(
377 self.coords, self.influence_dist, self.cutoffs, self.need_neigh
378 )
380 @check_call_wrapper
381 def create_paddings(
382 self, cell, pbc, contributing_coords, contributing_species_code
383 ):
384 # Cast things passed through kimpy to numpy arrays
385 cell = np.asarray(cell, dtype=c_double)
386 pbc = np.asarray(pbc, dtype=c_int)
387 contributing_coords = np.asarray(contributing_coords, dtype=c_double)
389 return kimpy.neighlist.create_paddings(
390 self.influence_dist,
391 cell,
392 pbc,
393 contributing_coords,
394 contributing_species_code,
395 )
397 def update(self, atoms, species_map):
398 """Create the neighbor list along with the other required
399 parameters (which are stored as instance attributes). The
400 required parameters are:
402 - num_particles
403 - coords
404 - particle_contributing
405 - species_code
407 Note that the KIM API requires a neighbor list that has indices
408 corresponding to each atom.
409 """
411 # Get info from Atoms object
412 cell = np.asarray(atoms.get_cell(), dtype=c_double)
413 pbc = np.asarray(atoms.get_pbc(), dtype=c_int)
414 contributing_coords = np.asarray(atoms.get_positions(), dtype=c_double)
415 self.num_contributing_particles = atoms.get_global_number_of_atoms()
416 num_contributing = self.num_contributing_particles
418 # Species support and code
419 try:
420 contributing_species_code = np.array(
421 [species_map[s] for s in atoms.get_chemical_symbols()],
422 dtype=c_int,
423 )
424 except KeyError as e:
425 raise RuntimeError(
426 'Species not supported by KIM model; {}'.format(str(e))
427 )
429 if pbc.any(): # Need padding atoms
430 # Create padding atoms
432 (
433 padding_coords,
434 padding_species_code,
435 self.padding_image_of,
436 ) = self.create_paddings(
437 cell, pbc, contributing_coords, contributing_species_code
438 )
439 num_padding = padding_species_code.size
441 self.num_particles = [num_contributing + num_padding]
442 self.coords = np.concatenate((contributing_coords, padding_coords))
443 self.species_code = np.concatenate(
444 (contributing_species_code, padding_species_code)
445 )
446 self.particle_contributing = [1] * num_contributing + [
447 0
448 ] * num_padding
449 self.need_neigh = [1] * self.num_particles[0]
450 if not self.padding_need_neigh:
451 self.need_neigh[num_contributing:] = 0
453 else: # Do not need padding atoms
454 self.padding_image_of = []
455 self.num_particles = [num_contributing]
456 self.coords = contributing_coords
457 self.species_code = contributing_species_code
458 self.particle_contributing = [1] * num_contributing
459 self.need_neigh = self.particle_contributing
461 # Create neighborlist
462 self.build()
464 self.last_update_positions = atoms.get_positions()
466 if self.debug:
467 print('Debug: called update_kimpy_neigh')
468 print()