Coverage for ase/calculators/kim/kimmodel.py: 94.57%

184 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1""" 

2ASE Calculator for interatomic models compatible with the Knowledgebase 

3of Interatomic Models (KIM) application programming interface (API). 

4Written by: 

5 

6Mingjian Wen 

7Daniel S. Karls 

8University of Minnesota 

9""" 

10 

11import numpy as np 

12 

13from ase.calculators.calculator import Calculator, compare_atoms 

14 

15from . import kimpy_wrappers, neighborlist 

16 

17 

18class KIMModelData: 

19 """Initializes and subsequently stores the KIM API Portable Model 

20 object, KIM API ComputeArguments object, and the neighbor list 

21 object used by instances of KIMModelCalculator. Also stores the 

22 arrays which are registered in the KIM API and which are used to 

23 communicate with the model. 

24 """ 

25 

26 def __init__(self, model_name, ase_neigh, neigh_skin_ratio, debug=False): 

27 self.model_name = model_name 

28 self.ase_neigh = ase_neigh 

29 self.debug = debug 

30 

31 # Initialize KIM API Portable Model object and ComputeArguments object 

32 self.kim_model, self.compute_args = self._init_kim() 

33 

34 self.species_map = self._create_species_map() 

35 

36 # Ask model to provide information relevant for neighbor list 

37 # construction 

38 ( 

39 model_influence_dist, 

40 model_cutoffs, 

41 padding_not_require_neigh, 

42 ) = self.get_model_neighbor_list_parameters() 

43 

44 # Initialize neighbor list object 

45 self.neigh = self._init_neigh( 

46 neigh_skin_ratio, 

47 model_influence_dist, 

48 model_cutoffs, 

49 padding_not_require_neigh, 

50 ) 

51 

52 def _init_kim(self): 

53 """Create the KIM API Portable Model object and KIM API ComputeArguments 

54 object 

55 """ 

56 if self.kim_initialized: 

57 return None 

58 

59 kim_model = kimpy_wrappers.PortableModel(self.model_name, self.debug) 

60 

61 # KIM API model object is what actually creates/destroys the 

62 # ComputeArguments object, so we must pass it as a parameter 

63 compute_args = kim_model.compute_arguments_create() 

64 

65 return kim_model, compute_args 

66 

67 def _init_neigh( 

68 self, 

69 neigh_skin_ratio, 

70 model_influence_dist, 

71 model_cutoffs, 

72 padding_not_require_neigh, 

73 ): 

74 """Initialize neighbor list, either an ASE-native neighborlist 

75 or one created using the neighlist module in kimpy 

76 """ 

77 neigh_list_object_type = ( 

78 neighborlist.ASENeighborList 

79 if self.ase_neigh 

80 else neighborlist.KimpyNeighborList 

81 ) 

82 return neigh_list_object_type( 

83 self.compute_args, 

84 neigh_skin_ratio, 

85 model_influence_dist, 

86 model_cutoffs, 

87 padding_not_require_neigh, 

88 self.debug, 

89 ) 

90 

91 def get_model_neighbor_list_parameters(self): 

92 model_influence_dist = self.kim_model.get_influence_distance() 

93 ( 

94 model_cutoffs, 

95 padding_not_require_neigh, 

96 ) = self.kim_model.get_neighbor_list_cutoffs_and_hints() 

97 

98 return model_influence_dist, model_cutoffs, padding_not_require_neigh 

99 

100 def update_compute_args_pointers(self, energy, forces): 

101 self.compute_args.update( 

102 self.num_particles, 

103 self.species_code, 

104 self._particle_contributing, 

105 self.coords, 

106 energy, 

107 forces, 

108 ) 

109 

110 def _create_species_map(self): 

111 """Get all the supported species of the KIM model and the 

112 corresponding integer codes used by the model 

113 

114 Returns 

115 ------- 

116 species_map : dict 

117 key : str 

118 chemical symbols (e.g. "Ar") 

119 value : int 

120 species integer code (e.g. 1) 

121 """ 

122 supported_species, codes = self._get_model_supported_species_and_codes() 

123 species_map = {} 

124 for i, spec in enumerate(supported_species): 

125 species_map[spec] = codes[i] 

126 if self.debug: 

127 print( 

128 'Species {} is supported and its code is: {}'.format( 

129 spec, codes[i] 

130 ) 

131 ) 

132 

133 return species_map 

134 

135 @property 

136 def padding_image_of(self): 

137 return self.neigh.padding_image_of 

138 

139 @property 

140 def num_particles(self): 

141 return self.neigh.num_particles 

142 

143 @property 

144 def coords(self): 

145 return self.neigh.coords 

146 

147 @property 

148 def _particle_contributing(self): 

149 return self.neigh.particle_contributing 

150 

151 @property 

152 def species_code(self): 

153 return self.neigh.species_code 

154 

155 @property 

156 def kim_initialized(self): 

157 return hasattr(self, 'kim_model') 

158 

159 @property 

160 def _neigh_initialized(self): 

161 return hasattr(self, 'neigh') 

162 

163 @property 

164 def _get_model_supported_species_and_codes(self): 

165 return self.kim_model.get_model_supported_species_and_codes 

166 

167 

168class KIMModelCalculator(Calculator): 

169 """Calculator that works with KIM Portable Models (PMs). 

170 

171 Calculator that carries out direct communication between ASE and a 

172 KIM Portable Model (PM) through the kimpy library (which provides a 

173 set of python bindings to the KIM API). 

174 

175 Parameters 

176 ---------- 

177 model_name : str 

178 The unique identifier assigned to the interatomic model (for 

179 details, see https://openkim.org/doc/schema/kim-ids) 

180 

181 ase_neigh : bool, optional 

182 False (default): Use kimpy's neighbor list library 

183 

184 True: Use ASE's internal neighbor list mechanism (usually slower 

185 than the kimpy neighlist library) 

186 

187 neigh_skin_ratio : float, optional 

188 Used to determine the neighbor list cutoff distance, r_neigh, 

189 through the relation r_neigh = (1 + neigh_skin_ratio) * rcut, 

190 where rcut is the model's influence distance. (Default: 0.2) 

191 

192 release_GIL : bool, optional 

193 Whether to release python GIL. Releasing the GIL allows a KIM 

194 model to run with multiple concurrent threads. (Default: False) 

195 

196 debug : bool, optional 

197 If True, detailed information is printed to stdout. (Default: 

198 False) 

199 """ 

200 

201 implemented_properties = ['energy', 'free_energy', 'forces', 'stress'] 

202 

203 ignored_changes = {'initial_charges', 'initial_magmoms'} 

204 

205 def __init__( 

206 self, 

207 model_name, 

208 ase_neigh=False, 

209 neigh_skin_ratio=0.2, 

210 release_GIL=False, 

211 debug=False, 

212 *args, 

213 **kwargs, 

214 ): 

215 super().__init__(*args, **kwargs) 

216 

217 self.model_name = model_name 

218 self.release_GIL = release_GIL 

219 self.debug = debug 

220 

221 if neigh_skin_ratio < 0: 

222 raise ValueError('Argument "neigh_skin_ratio" must be non-negative') 

223 self.neigh_skin_ratio = neigh_skin_ratio 

224 

225 # Model output 

226 self.energy = None 

227 self.forces = None 

228 

229 # Create KIMModelData object. This will take care of creating 

230 # and storing the KIM API Portable Model object, KIM API 

231 # ComputeArguments object, and the neighbor list object that 

232 # our calculator needs 

233 self._kimmodeldata = KIMModelData( 

234 self.model_name, ase_neigh, self.neigh_skin_ratio, self.debug 

235 ) 

236 

237 self._parameters_changed = False 

238 

239 def __enter__(self): 

240 return self 

241 

242 def __exit__(self, exc_type, value, traceback): 

243 pass 

244 

245 def __repr__(self): 

246 return f'KIMModelCalculator(model_name={self.model_name})' 

247 

248 def calculate( 

249 self, 

250 atoms=None, 

251 properties=None, 

252 system_changes=None, 

253 ): 

254 """ 

255 Inherited method from the ase Calculator class that is called by 

256 get_property() 

257 

258 Parameters 

259 ---------- 

260 atoms : Atoms 

261 Atoms object whose properties are desired 

262 

263 properties : list of str 

264 List of what needs to be calculated. Can be any combination 

265 of 'energy', 'forces' and 'stress'. 

266 

267 system_changes : list of str 

268 List of what has changed since last calculation. Can be any 

269 combination of these six: 'positions', 'numbers', 'cell', 

270 and 'pbc'. 

271 """ 

272 

273 if system_changes is None: 

274 system_changes = ['positions', 'numbers', 'cell', 'pbc'] 

275 if properties is None: 

276 properties = ['energy', 'forces', 'stress'] 

277 super().calculate(atoms, properties, system_changes) 

278 

279 if self._parameters_changed: 

280 self._parameters_changed = False 

281 

282 if system_changes: 

283 # Ask model to update all of its parameters and the parameters 

284 # related to the neighbor list(s). This update is necessary to do 

285 # here since the user will generally have made changes the model 

286 # parameters since the last time an update was performed and we 

287 # need to ensure that any properties calculated here are made using 

288 # the up-to-date model and neighbor list parameters. 

289 self._model_refresh_and_update_neighbor_list_parameters() 

290 

291 if self._need_neigh_update(atoms, system_changes): 

292 self._update_neigh(atoms, self._species_map) 

293 self.energy = np.array([0.0], dtype=kimpy_wrappers.c_double) 

294 self.forces = np.zeros( 

295 [self._num_particles[0], 3], dtype=kimpy_wrappers.c_double 

296 ) 

297 self._update_compute_args_pointers(self.energy, self.forces) 

298 else: 

299 self._update_kim_coords(atoms) 

300 

301 self._kim_model.compute(self._compute_args, self.release_GIL) 

302 

303 energy = self.energy[0] 

304 forces = self._assemble_padding_forces() 

305 

306 try: 

307 volume = atoms.get_volume() 

308 stress = self._compute_virial_stress( 

309 self.forces, self._coords, volume 

310 ) 

311 except ValueError: # Volume cannot be computed 

312 stress = None 

313 

314 # Quantities passed back to ASE 

315 self.results['energy'] = energy 

316 self.results['free_energy'] = energy 

317 self.results['forces'] = forces 

318 self.results['stress'] = stress 

319 

320 def check_state(self, atoms, tol=1e-15): 

321 # Check for change in atomic configuration (positions or pbc) 

322 system_changes = compare_atoms( 

323 self.atoms, atoms, excluded_properties=self.ignored_changes 

324 ) 

325 

326 # Check if model parameters were changed 

327 if self._parameters_changed: 

328 system_changes.append('calculator') 

329 

330 return system_changes 

331 

332 def _assemble_padding_forces(self): 

333 """ 

334 Assemble forces on padding atoms back to contributing atoms. 

335 

336 Parameters 

337 ---------- 

338 forces : 2D array of doubles 

339 Forces on both contributing and padding atoms 

340 

341 num_contrib: int 

342 Number of contributing atoms 

343 

344 padding_image_of : 1D array of int 

345 Atom number, of which the padding atom is an image 

346 

347 

348 Returns 

349 ------- 

350 Total forces on contributing atoms. 

351 """ 

352 

353 total_forces = np.array(self.forces[: self._num_contributing_particles]) 

354 

355 if self._padding_image_of.size != 0: 

356 pad_forces = self.forces[self._num_contributing_particles :] 

357 for f, org_index in zip(pad_forces, self._padding_image_of): 

358 total_forces[org_index] += f 

359 

360 return total_forces 

361 

362 @staticmethod 

363 def _compute_virial_stress(forces, coords, volume): 

364 """Compute the virial stress in Voigt notation. 

365 

366 Parameters 

367 ---------- 

368 forces : 2D array 

369 Partial forces on all atoms (padding included) 

370 

371 coords : 2D array 

372 Coordinates of all atoms (padding included) 

373 

374 volume : float 

375 Volume of cell 

376 

377 Returns 

378 ------- 

379 stress : 1D array 

380 stress in Voigt order (xx, yy, zz, yz, xz, xy) 

381 """ 

382 stress = np.zeros(6) 

383 stress[0] = -np.dot(forces[:, 0], coords[:, 0]) / volume 

384 stress[1] = -np.dot(forces[:, 1], coords[:, 1]) / volume 

385 stress[2] = -np.dot(forces[:, 2], coords[:, 2]) / volume 

386 stress[3] = -np.dot(forces[:, 1], coords[:, 2]) / volume 

387 stress[4] = -np.dot(forces[:, 0], coords[:, 2]) / volume 

388 stress[5] = -np.dot(forces[:, 0], coords[:, 1]) / volume 

389 

390 return stress 

391 

392 @property 

393 def _update_compute_args_pointers(self): 

394 return self._kimmodeldata.update_compute_args_pointers 

395 

396 @property 

397 def _kim_model(self): 

398 return self._kimmodeldata.kim_model 

399 

400 @property 

401 def _compute_args(self): 

402 return self._kimmodeldata.compute_args 

403 

404 @property 

405 def _num_particles(self): 

406 return self._kimmodeldata.num_particles 

407 

408 @property 

409 def _coords(self): 

410 return self._kimmodeldata.coords 

411 

412 @property 

413 def _padding_image_of(self): 

414 return self._kimmodeldata.padding_image_of 

415 

416 @property 

417 def _species_map(self): 

418 return self._kimmodeldata.species_map 

419 

420 @property 

421 def _neigh(self): 

422 # WARNING: This property is underscored for a reason! The 

423 # neighborlist(s) itself (themselves) may not be up to date with 

424 # respect to changes that have been made to the model's parameters, or 

425 # even since the positions in the Atoms object may have changed. 

426 # Neighbor lists are only potentially updated inside the ``calculate`` 

427 # method. 

428 return self._kimmodeldata.neigh 

429 

430 @property 

431 def _num_contributing_particles(self): 

432 return self._neigh.num_contributing_particles 

433 

434 @property 

435 def _update_kim_coords(self): 

436 return self._neigh.update_kim_coords 

437 

438 @property 

439 def _need_neigh_update(self): 

440 return self._neigh.need_neigh_update 

441 

442 @property 

443 def _update_neigh(self): 

444 return self._neigh.update 

445 

446 @property 

447 def parameters_metadata(self): 

448 return self._kim_model.parameters_metadata 

449 

450 @property 

451 def parameter_names(self): 

452 return self._kim_model.parameter_names 

453 

454 @property 

455 def get_parameters(self): 

456 # Ask model to update all of its parameters and the parameters related 

457 # to the neighbor list(s). This update is necessary to do here since 

458 # the user will generally have made changes the model parameters since 

459 # the last time an update was performed and we need to ensure the 

460 # parameters returned by this method are fully up to date. 

461 self._model_refresh_and_update_neighbor_list_parameters() 

462 

463 return self._kim_model.get_parameters 

464 

465 def set_parameters(self, **kwargs): 

466 parameters = self._kim_model.set_parameters(**kwargs) 

467 self._parameters_changed = True 

468 

469 return parameters 

470 

471 def _model_refresh_and_update_neighbor_list_parameters(self): 

472 """ 

473 Call the model's refresh routine and update the neighbor list object 

474 for any necessary changes arising from changes to the model parameters, 

475 e.g. a change in one of its cutoffs. After a model's parameters have 

476 been changed, this method *must* be called before calling the model's 

477 compute routine. 

478 """ 

479 self._kim_model.clear_then_refresh() 

480 

481 # Update neighbor list parameters 

482 ( 

483 model_influence_dist, 

484 model_cutoffs, 

485 padding_not_require_neigh, 

486 ) = self._kimmodeldata.get_model_neighbor_list_parameters() 

487 

488 self._neigh.set_neigh_parameters( 

489 self.neigh_skin_ratio, 

490 model_influence_dist, 

491 model_cutoffs, 

492 padding_not_require_neigh, 

493 )