Coverage for ase/calculators/eam.py: 89.77%

440 statements  

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

1"""Calculator for the Embedded Atom Method Potential""" 

2 

3# eam.py 

4# Embedded Atom Method Potential 

5# These routines integrate with the ASE simulation environment 

6# Paul White (Oct 2012) 

7# UNCLASSIFIED 

8# License: See accompanying license files for details 

9 

10import os 

11 

12import numpy as np 

13from scipy.interpolate import InterpolatedUnivariateSpline as spline 

14 

15from ase.calculators.calculator import Calculator, all_changes 

16from ase.data import chemical_symbols 

17from ase.neighborlist import NeighborList 

18from ase.stress import full_3x3_to_voigt_6_stress 

19from ase.units import Bohr, Hartree 

20 

21 

22class EAM(Calculator): 

23 r"""EAM Interface Documentation 

24 

25 Introduction 

26 ============ 

27 

28 The Embedded Atom Method (EAM) [1]_ is a classical potential which is 

29 good for modelling metals, particularly fcc materials. Because it is 

30 an equiaxial potential the EAM does not model directional bonds 

31 well. However, the Angular Dependent Potential (ADP) [2]_ which is an 

32 extended version of EAM is able to model directional bonds and is also 

33 included in the EAM calculator. 

34 

35 Generally all that is required to use this calculator is to supply a 

36 potential file or as a set of functions that describe the potential. 

37 The files containing the potentials for this calculator are not 

38 included but many suitable potentials can be downloaded from The 

39 Interatomic Potentials Repository Project at 

40 https://www.ctcms.nist.gov/potentials/ 

41 

42 Theory 

43 ====== 

44 

45 A single element EAM potential is defined by three functions: the 

46 embedded energy, electron density and the pair potential. A two 

47 element alloy contains the individual three functions for each element 

48 plus cross pair interactions. The ADP potential has two additional 

49 sets of data to define the dipole and quadrupole directional terms for 

50 each alloy and their cross interactions. 

51 

52 The total energy :math:`E_{\rm tot}` of an arbitrary arrangement of atoms is 

53 given by the EAM potential as 

54 

55 .. math:: 

56 E_\text{tot} = 

57 \sum_i F(\bar\rho_i) + \frac{1}{2}\sum_{i\ne j} \phi(r_{ij}) 

58 

59 and 

60 

61 .. math:: 

62 \bar\rho_i = \sum_j \rho(r_{ij}) 

63 

64 where :math:`F` is an embedding function, namely the energy to embed an 

65 atom :math:`i` in the combined electron density :math:`\bar\rho_i` which is 

66 contributed from each of its neighbouring atoms :math:`j` by an amount 

67 :math:`\rho(r_{ij})`, :math:`\phi(r_{ij})` is the pair potential function 

68 representing the energy in bond :math:`ij` which is due to the 

69 short-range electro-static interaction between atoms, and :math:`r_{ij}` 

70 is the distance between an atom and its neighbour for that bond. 

71 

72 The ADP potential is defined as 

73 

74 .. math:: 

75 E_\text{tot} = \sum_i F(\bar\rho_i) 

76 + \frac{1}{2}\sum_{i\ne j} \phi(r_{ij}) 

77 + \frac{1}{2} \sum_{i,\alpha} (\mu_i^\alpha)^2 

78 + \frac{1}{2} \sum_{i,\alpha,\beta} (\lambda_i^{\alpha\beta})^2 

79 - \frac{1}{6} \sum_i \nu_i^2 

80 

81 where :math:`\mu_i^\alpha` is the dipole vector, 

82 :math:`\lambda_i^{\alpha\beta}` 

83 is the quadrupole tensor and :math:`\nu_i` is the trace of 

84 :math:`\lambda_i^{\alpha\beta}`. 

85 

86 The fs potential is defined as 

87 

88 .. math:: 

89 E_i = F_\alpha (\sum_{j\neq i} \rho_{\alpha \beta}(r_{ij})) 

90 + \frac{1}{2}\sum_{j\neq i}\phi_{\alpha \beta}(r_{ij}) 

91 

92 where :math:`\alpha` and :math:`\beta` are element types of atoms. 

93 This form 

94 is similar to original EAM formula above, except that :math:`\rho` and 

95 :math:`\phi` are determined by element types. 

96 

97 Running the Calculator 

98 ====================== 

99 

100 EAM calculates the cohesive atom energy, forces and 

101 stress. Internally the potential functions are defined by splines 

102 which may be directly supplied or created by reading the spline 

103 points from a data file from which a spline function is created. 

104 The LAMMPS compatible ``.alloy``, ``.fs`` and ``.adp`` formats are 

105 supported. The LAMMPS ``.eam`` format is slightly different from 

106 the ``.alloy`` format and is currently not supported. 

107 

108 For example:: 

109 

110 from ase.calculators.eam import EAM 

111 

112 mishin = EAM(potential='Al99.eam.alloy') 

113 mishin.write_potential('new.eam.alloy') 

114 mishin.plot() 

115 

116 slab.calc = mishin 

117 slab.get_potential_energy() 

118 slab.get_forces() 

119 slab.get_stress() 

120 

121 The breakdown of energy contribution from the indvidual components are 

122 stored in the calculator instance ``.results['energy_components']`` 

123 

124 Arguments: 

125 ========== 

126 

127 ========================= ================================================ 

128 Keyword Description 

129 ========================= ================================================ 

130 ``potential`` file of potential in ``.eam``, ``.alloy``, 

131 ``.adp`` or ``.fs`` 

132 format or file object 

133 (This is generally all you need to supply). 

134 For file object the ``form`` argument is 

135 required 

136 

137 ``elements[N]`` array of N element abbreviations 

138 

139 ``embedded_energy[N]`` arrays of embedded energy functions 

140 

141 ``electron_density[N]`` arrays of electron density functions 

142 

143 ``phi[N,N]`` arrays of pair potential functions 

144 

145 ``d_embedded_energy[N]`` arrays of derivative embedded energy functions 

146 

147 ``d_electron_density[N]`` arrays of derivative electron density functions 

148 

149 ``d_phi[N,N]`` arrays of derivative pair potentials functions 

150 

151 ``d[N,N], q[N,N]`` ADP dipole and quadrupole function 

152 

153 ``d_d[N,N], d_q[N,N]`` ADP dipole and quadrupole derivative functions 

154 

155 ``skin`` skin distance passed to NeighborList(). 

156 If no atom 

157 has moved more than the skin-distance since the 

158 last 

159 call to the ``update()`` method then the neighbor 

160 list can be reused. Defaults to 1.0. 

161 

162 ``form`` the form of the potential 

163 ``eam``, ``alloy``, ``adp`` or 

164 ``fs``. This will be determined from the file 

165 suffix 

166 or must be set if using equations or file object 

167 

168 ========================= ================================================ 

169 

170 

171 Additional parameters for writing potential files 

172 ================================================= 

173 

174 The following parameters are only required for writing a potential in 

175 ``.alloy``, ``.adp`` or ``fs`` format file. 

176 

177 ========================= ================================================ 

178 Keyword Description 

179 ========================= ================================================ 

180 ``header`` Three line text header. Default is standard 

181 message. 

182 

183 ``Z[N]`` Array of atomic number of each element 

184 

185 ``mass[N]`` Atomic mass of each element 

186 

187 ``a[N]`` Array of lattice parameters for each element 

188 

189 ``lattice[N]`` Lattice type 

190 

191 ``nrho`` No. of rho samples along embedded energy curve 

192 

193 ``drho`` Increment for sampling density 

194 

195 ``nr`` No. of radial points along density and pair 

196 potential curves 

197 

198 ``dr`` Increment for sampling radius 

199 

200 ========================= ================================================ 

201 

202 Special features 

203 ================ 

204 

205 ``.plot()`` 

206 Plots the individual functions. This may be called from multiple EAM 

207 potentials to compare the shape of the individual curves. This 

208 function requires the installation of the Matplotlib libraries. 

209 

210 Notes/Issues 

211 ============ 

212 

213 * Although currently not fast, this calculator can be good for trying 

214 small calculations or for creating new potentials by matching baseline 

215 data such as from DFT results. The format for these potentials is 

216 compatible with LAMMPS_ and so can be used either directly by LAMMPS or 

217 with the ASE LAMMPS calculator interface. 

218 

219 * Supported formats are the LAMMPS_ ``.alloy`` and ``.adp``. The 

220 ``.eam`` format is currently not supported. The form of the 

221 potential will be determined from the file suffix. 

222 

223 * Any supplied values will override values read from the file. 

224 

225 * The derivative functions, if supplied, are only used to calculate 

226 forces. 

227 

228 * There is a bug in early versions of scipy that will cause eam.py to 

229 crash when trying to evaluate splines of a potential with one 

230 neighbor such as caused by evaluating a dimer. 

231 

232 .. _LAMMPS: https://www.lammps.org/ 

233 

234 .. [1] M.S. Daw and M.I. Baskes, Phys. Rev. Letters 50 (1983) 

235 1285. 

236 

237 .. [2] Y. Mishin, M.J. Mehl, and D.A. Papaconstantopoulos, 

238 Acta Materialia 53 2005 4029--4041. 

239 """ 

240 

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

242 

243 default_parameters = dict( 

244 skin=1.0, 

245 potential=None, 

246 header=[ 

247 'EAM/ADP potential file\n', 

248 'Generated from eam.py\n', 

249 'blank\n', 

250 ], 

251 ) 

252 

253 def __init__( 

254 self, 

255 restart=None, 

256 ignore_bad_restart_file=Calculator._deprecated, 

257 label=os.curdir, 

258 atoms=None, 

259 form=None, 

260 **kwargs, 

261 ): 

262 

263 self.form = form 

264 

265 if 'potential' in kwargs: 

266 self.read_potential(kwargs['potential']) 

267 

268 Calculator.__init__( 

269 self, restart, ignore_bad_restart_file, label, atoms, **kwargs 

270 ) 

271 

272 valid_args = ( 

273 'potential', 

274 'elements', 

275 'header', 

276 'drho', 

277 'dr', 

278 'cutoff', 

279 'atomic_number', 

280 'mass', 

281 'a', 

282 'lattice', 

283 'embedded_energy', 

284 'electron_density', 

285 'phi', 

286 # derivatives 

287 'd_embedded_energy', 

288 'd_electron_density', 

289 'd_phi', 

290 'd', 

291 'q', 

292 'd_d', 

293 'd_q', # adp terms 

294 'skin', 

295 'Z', 

296 'nr', 

297 'nrho', 

298 'mass', 

299 ) 

300 

301 # set any additional keyword arguments 

302 for arg, val in self.parameters.items(): 

303 if arg in valid_args: 

304 if getattr(self, arg, None) is None: 

305 setattr(self, arg, val) 

306 else: 

307 raise RuntimeError( 

308 f'unknown keyword arg "{arg}" : not in {valid_args}' 

309 ) 

310 

311 def set_form(self, name): 

312 """set the form variable based on the file name suffix""" 

313 extension = os.path.splitext(name)[1] 

314 

315 if extension == '.eam': 

316 self.form = 'eam' 

317 elif extension == '.alloy': 

318 self.form = 'alloy' 

319 elif extension == '.adp': 

320 self.form = 'adp' 

321 elif extension == '.fs': 

322 self.form = 'fs' 

323 else: 

324 raise RuntimeError(f'unknown file extension type: {extension}') 

325 

326 def read_potential(self, filename): 

327 """Reads a LAMMPS EAM file in alloy or adp format 

328 and creates the interpolation functions from the data 

329 """ 

330 

331 if isinstance(filename, str): 

332 with open(filename) as fd: 

333 self._read_potential(fd) 

334 else: 

335 fd = filename 

336 self._read_potential(fd) 

337 

338 def _read_potential(self, fd): 

339 if self.form is None: 

340 self.set_form(fd.name) 

341 

342 lines = fd.readlines() 

343 

344 def lines_to_list(lines): 

345 """Make data one long line so as not to care how its formatted""" 

346 data = [] 

347 for line in lines: 

348 data.extend(line.split()) 

349 return data 

350 

351 if self.form == 'eam': # single element eam file (aka funcfl) 

352 self.header = lines[:1] 

353 

354 data = lines_to_list(lines[1:]) 

355 

356 # eam form is just like an alloy form for one element 

357 

358 self.Nelements = 1 

359 self.elements = [chemical_symbols[int(data[0])]] 

360 self.Z = np.array([data[0]], dtype=int) 

361 self.mass = np.array([data[1]], dtype=float) 

362 self.a = np.array([data[2]], dtype=float) 

363 self.lattice = [data[3]] 

364 

365 self.nrho = int(data[4]) 

366 self.drho = float(data[5]) 

367 self.nr = int(data[6]) 

368 self.dr = float(data[7]) 

369 self.cutoff = float(data[8]) 

370 

371 n = 9 + self.nrho 

372 self.embedded_data = np.array([np.float64(data[9:n])]) 

373 

374 self.rphi_data = np.zeros([self.Nelements, self.Nelements, self.nr]) 

375 

376 effective_charge = np.float64(data[n : n + self.nr]) 

377 # convert effective charges to rphi according to 

378 # https://docs.lammps.org/pair_eam.html 

379 self.rphi_data[0, 0] = Bohr * Hartree * (effective_charge**2) 

380 

381 self.density_data = np.array( 

382 [np.float64(data[n + self.nr : n + 2 * self.nr])] 

383 ) 

384 

385 elif self.form in ['alloy', 'adp']: 

386 self.header = lines[:3] 

387 i = 3 

388 

389 data = lines_to_list(lines[i:]) 

390 

391 self.Nelements = int(data[0]) 

392 d = 1 

393 self.elements = data[d : d + self.Nelements] 

394 d += self.Nelements 

395 

396 self.nrho = int(data[d]) 

397 self.drho = float(data[d + 1]) 

398 self.nr = int(data[d + 2]) 

399 self.dr = float(data[d + 3]) 

400 self.cutoff = float(data[d + 4]) 

401 

402 self.embedded_data = np.zeros([self.Nelements, self.nrho]) 

403 self.density_data = np.zeros([self.Nelements, self.nr]) 

404 self.Z = np.zeros([self.Nelements], dtype=int) 

405 self.mass = np.zeros([self.Nelements]) 

406 self.a = np.zeros([self.Nelements]) 

407 self.lattice = [] 

408 d += 5 

409 

410 # reads in the part of the eam file for each element 

411 for elem in range(self.Nelements): 

412 self.Z[elem] = int(data[d]) 

413 self.mass[elem] = float(data[d + 1]) 

414 self.a[elem] = float(data[d + 2]) 

415 self.lattice.append(data[d + 3]) 

416 d += 4 

417 

418 self.embedded_data[elem] = np.float64(data[d : (d + self.nrho)]) 

419 d += self.nrho 

420 self.density_data[elem] = np.float64(data[d : (d + self.nr)]) 

421 d += self.nr 

422 

423 # reads in the r*phi data for each interaction between elements 

424 self.rphi_data = np.zeros([self.Nelements, self.Nelements, self.nr]) 

425 

426 for i in range(self.Nelements): 

427 for j in range(i + 1): 

428 self.rphi_data[j, i] = np.float64(data[d : (d + self.nr)]) 

429 d += self.nr 

430 

431 elif self.form == 'fs': 

432 self.header = lines[:3] 

433 i = 3 

434 

435 data = lines_to_list(lines[i:]) 

436 

437 self.Nelements = int(data[0]) 

438 d = 1 

439 self.elements = data[d : d + self.Nelements] 

440 d += self.Nelements 

441 

442 self.nrho = int(data[d]) 

443 self.drho = float(data[d + 1]) 

444 self.nr = int(data[d + 2]) 

445 self.dr = float(data[d + 3]) 

446 self.cutoff = float(data[d + 4]) 

447 

448 self.embedded_data = np.zeros([self.Nelements, self.nrho]) 

449 self.density_data = np.zeros( 

450 [self.Nelements, self.Nelements, self.nr] 

451 ) 

452 self.Z = np.zeros([self.Nelements], dtype=int) 

453 self.mass = np.zeros([self.Nelements]) 

454 self.a = np.zeros([self.Nelements]) 

455 self.lattice = [] 

456 d += 5 

457 

458 # reads in the part of the eam file for each element 

459 for elem in range(self.Nelements): 

460 self.Z[elem] = int(data[d]) 

461 self.mass[elem] = float(data[d + 1]) 

462 self.a[elem] = float(data[d + 2]) 

463 self.lattice.append(data[d + 3]) 

464 d += 4 

465 

466 self.embedded_data[elem] = np.float64(data[d : (d + self.nrho)]) 

467 d += self.nrho 

468 self.density_data[elem, :, :] = np.float64( 

469 data[d : (d + self.nr * self.Nelements)] 

470 ).reshape([self.Nelements, self.nr]) 

471 d += self.nr * self.Nelements 

472 

473 # reads in the r*phi data for each interaction between elements 

474 self.rphi_data = np.zeros([self.Nelements, self.Nelements, self.nr]) 

475 

476 for i in range(self.Nelements): 

477 for j in range(i + 1): 

478 self.rphi_data[j, i] = np.float64(data[d : (d + self.nr)]) 

479 d += self.nr 

480 

481 self.r = np.arange(0, self.nr) * self.dr 

482 self.rho = np.arange(0, self.nrho) * self.drho 

483 

484 # choose the set_splines method according to the type 

485 if self.form == 'fs': 

486 self.set_fs_splines() 

487 else: 

488 self.set_splines() 

489 

490 if self.form == 'adp': 

491 self.read_adp_data(data, d) 

492 self.set_adp_splines() 

493 

494 def set_splines(self): 

495 # this section turns the file data into three functions (and 

496 # derivative functions) that define the potential 

497 self.embedded_energy = np.empty(self.Nelements, object) 

498 self.electron_density = np.empty(self.Nelements, object) 

499 self.d_embedded_energy = np.empty(self.Nelements, object) 

500 self.d_electron_density = np.empty(self.Nelements, object) 

501 

502 for i in range(self.Nelements): 

503 self.embedded_energy[i] = spline( 

504 self.rho, self.embedded_data[i], k=3 

505 ) 

506 self.electron_density[i] = spline(self.r, self.density_data[i], k=3) 

507 self.d_embedded_energy[i] = self.deriv(self.embedded_energy[i]) 

508 self.d_electron_density[i] = self.deriv(self.electron_density[i]) 

509 

510 self.phi = np.empty([self.Nelements, self.Nelements], object) 

511 self.d_phi = np.empty([self.Nelements, self.Nelements], object) 

512 

513 # ignore the first point of the phi data because it is forced 

514 # to go through zero due to the r*phi format in alloy and adp 

515 for i in range(self.Nelements): 

516 for j in range(i, self.Nelements): 

517 self.phi[i, j] = spline( 

518 self.r[1:], self.rphi_data[i, j][1:] / self.r[1:], k=3 

519 ) 

520 

521 self.d_phi[i, j] = self.deriv(self.phi[i, j]) 

522 

523 if j != i: 

524 self.phi[j, i] = self.phi[i, j] 

525 self.d_phi[j, i] = self.d_phi[i, j] 

526 

527 def set_fs_splines(self): 

528 self.embedded_energy = np.empty(self.Nelements, object) 

529 self.electron_density = np.empty( 

530 [self.Nelements, self.Nelements], object 

531 ) 

532 self.d_embedded_energy = np.empty(self.Nelements, object) 

533 self.d_electron_density = np.empty( 

534 [self.Nelements, self.Nelements], object 

535 ) 

536 

537 for i in range(self.Nelements): 

538 self.embedded_energy[i] = spline( 

539 self.rho, self.embedded_data[i], k=3 

540 ) 

541 self.d_embedded_energy[i] = self.deriv(self.embedded_energy[i]) 

542 for j in range(self.Nelements): 

543 self.electron_density[i, j] = spline( 

544 self.r, self.density_data[i, j], k=3 

545 ) 

546 self.d_electron_density[i, j] = self.deriv( 

547 self.electron_density[i, j] 

548 ) 

549 

550 self.phi = np.empty([self.Nelements, self.Nelements], object) 

551 self.d_phi = np.empty([self.Nelements, self.Nelements], object) 

552 

553 for i in range(self.Nelements): 

554 for j in range(i, self.Nelements): 

555 self.phi[i, j] = spline( 

556 self.r[1:], self.rphi_data[i, j][1:] / self.r[1:], k=3 

557 ) 

558 

559 self.d_phi[i, j] = self.deriv(self.phi[i, j]) 

560 

561 if j != i: 

562 self.phi[j, i] = self.phi[i, j] 

563 self.d_phi[j, i] = self.d_phi[i, j] 

564 

565 def set_adp_splines(self): 

566 self.d = np.empty([self.Nelements, self.Nelements], object) 

567 self.d_d = np.empty([self.Nelements, self.Nelements], object) 

568 self.q = np.empty([self.Nelements, self.Nelements], object) 

569 self.d_q = np.empty([self.Nelements, self.Nelements], object) 

570 

571 for i in range(self.Nelements): 

572 for j in range(i, self.Nelements): 

573 self.d[i, j] = spline(self.r[1:], self.d_data[i, j][1:], k=3) 

574 self.d_d[i, j] = self.deriv(self.d[i, j]) 

575 self.q[i, j] = spline(self.r[1:], self.q_data[i, j][1:], k=3) 

576 self.d_q[i, j] = self.deriv(self.q[i, j]) 

577 

578 # make symmetrical 

579 if j != i: 

580 self.d[j, i] = self.d[i, j] 

581 self.d_d[j, i] = self.d_d[i, j] 

582 self.q[j, i] = self.q[i, j] 

583 self.d_q[j, i] = self.d_q[i, j] 

584 

585 def read_adp_data(self, data, d): 

586 """read in the extra adp data from the potential file""" 

587 

588 self.d_data = np.zeros([self.Nelements, self.Nelements, self.nr]) 

589 # should be non symmetrical combinations of 2 

590 for i in range(self.Nelements): 

591 for j in range(i + 1): 

592 self.d_data[i, j] = self.d_data[j, i] = data[d : d + self.nr] 

593 d += self.nr 

594 

595 self.q_data = np.zeros([self.Nelements, self.Nelements, self.nr]) 

596 # should be non symmetrical combinations of 2 

597 for i in range(self.Nelements): 

598 for j in range(i + 1): 

599 self.q_data[i, j] = self.q_data[j, i] = data[d : d + self.nr] 

600 d += self.nr 

601 

602 def write_potential(self, filename, nc=1, numformat='%.17e'): 

603 """Writes out the potential in the format given by the form 

604 variable to 'filename' with a data format that is nc columns 

605 wide. Note: array lengths need to be an exact multiple of nc 

606 """ 

607 

608 with open(filename, 'wb') as fd: 

609 self._write_potential(fd, nc=nc, numformat=numformat) 

610 

611 def _write_potential(self, fd, nc, numformat): 

612 assert self.nr % nc == 0 

613 assert self.nrho % nc == 0 

614 

615 if self.form == 'eam': 

616 return self._write_potential_eam(fd, nc, numformat) 

617 

618 for i in range(3): 

619 fd.write(self.header[i].encode()) 

620 

621 fd.write(f'{self.Nelements} '.encode()) 

622 fd.write(' '.join(self.elements).encode() + b'\n') 

623 

624 fmt = f'%d {numformat} %d {numformat} {numformat}\n' 

625 fd.write( 

626 ( 

627 fmt % (self.nrho, self.drho, self.nr, self.dr, self.cutoff) 

628 ).encode() 

629 ) 

630 

631 # start of each section for each element 

632 # rs = np.linspace(0, self.nr * self.dr, self.nr) 

633 # rhos = np.linspace(0, self.nrho * self.drho, self.nrho) 

634 

635 rs = np.arange(0, self.nr) * self.dr 

636 rhos = np.arange(0, self.nrho) * self.drho 

637 

638 for i in range(self.Nelements): 

639 fd.write( 

640 ( 

641 '%d %f %f %s\n' 

642 % (self.Z[i], self.mass[i], self.a[i], str(self.lattice[i])) 

643 ).encode() 

644 ) 

645 np.savetxt( 

646 fd, 

647 self.embedded_energy[i](rhos).reshape(self.nrho // nc, nc), 

648 fmt=nc * [numformat], 

649 ) 

650 if self.form == 'fs': 

651 for j in range(self.Nelements): 

652 np.savetxt( 

653 fd, 

654 self.electron_density[i, j](rs).reshape( 

655 self.nr // nc, nc 

656 ), 

657 fmt=nc * [numformat], 

658 ) 

659 else: 

660 np.savetxt( 

661 fd, 

662 self.electron_density[i](rs).reshape(self.nr // nc, nc), 

663 fmt=nc * [numformat], 

664 ) 

665 

666 # write out the pair potentials in Lammps DYNAMO setfl format 

667 # as r*phi for alloy format 

668 for i in range(self.Nelements): 

669 for j in range(i + 1): 

670 np.savetxt( 

671 fd, 

672 (rs * self.phi[i, j](rs)).reshape(self.nr // nc, nc), 

673 fmt=nc * [numformat], 

674 ) 

675 

676 if self.form == 'adp': 

677 # these are the u(r) or dipole values 

678 for i in range(self.Nelements): 

679 for j in range(i + 1): 

680 np.savetxt(fd, self.d_data[i, j]) 

681 

682 # these are the w(r) or quadrupole values 

683 for i in range(self.Nelements): 

684 for j in range(i + 1): 

685 np.savetxt(fd, self.q_data[i, j]) 

686 

687 def _write_potential_eam(self, fd, nc, numformat): 

688 """Write the potential in the DYNAMO single-element funcfl format.""" 

689 

690 fd.write(self.header[0].encode()) 

691 

692 i = 0 # The DYNAMO funcfl format can store only one element. 

693 

694 vals = self.Z[i], self.mass[i], self.a[i], str(self.lattice[i]) 

695 fd.write(('%d %f %f %s\n' % vals).encode()) 

696 

697 fmt = f'%d {numformat} %d {numformat} {numformat}\n' 

698 vals = self.nrho, self.drho, self.nr, self.dr, self.cutoff 

699 fd.write((fmt % vals).encode()) 

700 

701 rs = np.arange(0, self.nr) * self.dr 

702 rhos = np.arange(0, self.nrho) * self.drho 

703 

704 arr = self.embedded_energy[i](rhos).reshape(self.nrho // nc, nc) 

705 np.savetxt(fd, arr, fmt=nc * [numformat]) 

706 

707 z2s = rs * self.phi[i, i](rs) / (Hartree * Bohr) 

708 z2s = np.where(np.isclose(z2s, 0.0), 0.0, z2s) 

709 arr = np.sqrt(z2s).reshape(self.nr // nc, nc) 

710 np.savetxt(fd, arr, fmt=nc * [numformat]) 

711 

712 arr = self.electron_density[i](rs).reshape(self.nr // nc, nc) 

713 np.savetxt(fd, arr, fmt=nc * [numformat]) 

714 

715 def update(self, atoms): 

716 # check all the elements are available in the potential 

717 self.Nelements = len(self.elements) 

718 elements = np.unique(atoms.get_chemical_symbols()) 

719 unavailable = np.logical_not( 

720 np.array([item in self.elements for item in elements]) 

721 ) 

722 

723 if np.any(unavailable): 

724 raise RuntimeError( 

725 'These elements are not in the potential: ' 

726 f'{elements[unavailable]}' 

727 ) 

728 

729 # cutoffs need to be a vector for NeighborList 

730 cutoffs = self.cutoff * np.ones(len(atoms)) 

731 

732 # convert the elements to an index of the position 

733 # in the eam format 

734 self.index = np.array( 

735 [self.elements.index(el) for el in atoms.get_chemical_symbols()] 

736 ) 

737 self.pbc = atoms.get_pbc() 

738 

739 # since we need the contribution of all neighbors to the 

740 # local electron density we cannot just calculate and use 

741 # one way neighbors 

742 self.neighbors = NeighborList( 

743 cutoffs, 

744 skin=self.parameters.skin, 

745 self_interaction=False, 

746 bothways=True, 

747 ) 

748 self.neighbors.update(atoms) 

749 

750 def calculate( 

751 self, atoms=None, properties=None, system_changes=all_changes 

752 ): 

753 """EAM Calculator 

754 

755 atoms: Atoms object 

756 Contains positions, unit-cell, ... 

757 properties: list of str 

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

759 of 'energy', 'forces' 

760 system_changes: list of str 

761 List of what has changed since last calculation. Can be 

762 any combination of these five: 'positions', 'numbers', 'cell', 

763 'pbc', 'initial_charges' and 'initial_magmoms'. 

764 """ 

765 

766 if properties is None: 

767 properties = ['energy'] 

768 Calculator.calculate(self, atoms, properties, system_changes) 

769 

770 # we shouldn't really recalc if charges or magmos change 

771 if len(system_changes) > 0: # something wrong with this way 

772 self.update(self.atoms) 

773 self.calculate_energy(self.atoms) 

774 

775 if 'forces' in properties or 'stress' in properties: 

776 self.calculate_forces(self.atoms) 

777 

778 # check we have all the properties requested 

779 for property in properties: 

780 if property not in self.results: 

781 if property == 'energy': 

782 self.calculate_energy(self.atoms) 

783 

784 if property in ['forces', 'stress']: 

785 self.calculate_forces(self.atoms) 

786 

787 # we need to remember the previous state of parameters 

788 

789 # if 'potential' in parameter_changes and potential != None: 

790 # self.read_potential(potential) 

791 

792 def calculate_energy(self, atoms): 

793 """Calculate the energy 

794 the energy is made up of the ionic or pair interaction and 

795 the embedding energy of each atom into the electron cloud 

796 generated by its neighbors 

797 """ 

798 

799 pair_energy = 0.0 

800 embedding_energy = 0.0 

801 mu_energy = 0.0 

802 lam_energy = 0.0 

803 trace_energy = 0.0 

804 

805 self.total_density = np.zeros(len(atoms)) 

806 if self.form == 'adp': 

807 self.mu = np.zeros([len(atoms), 3]) 

808 self.lam = np.zeros([len(atoms), 3, 3]) 

809 

810 for i in range(len(atoms)): # this is the atom to be embedded 

811 neighbors, offsets = self.neighbors.get_neighbors(i) 

812 offset = np.dot(offsets, atoms.get_cell()) 

813 

814 rvec = atoms.positions[neighbors] + offset - atoms.positions[i] 

815 

816 # calculate the distance to the nearest neighbors 

817 r = np.sqrt(np.sum(np.square(rvec), axis=1)) 

818 

819 nearest = np.arange(len(r))[r <= self.cutoff] 

820 for j_index in range(self.Nelements): 

821 use = self.index[neighbors[nearest]] == j_index 

822 if not use.any(): 

823 continue 

824 pair_energy += ( 

825 np.sum(self.phi[self.index[i], j_index](r[nearest][use])) 

826 / 2.0 

827 ) 

828 

829 if self.form == 'fs': 

830 density = np.sum( 

831 self.electron_density[j_index, self.index[i]]( 

832 r[nearest][use] 

833 ) 

834 ) 

835 else: 

836 density = np.sum( 

837 self.electron_density[j_index](r[nearest][use]) 

838 ) 

839 self.total_density[i] += density 

840 

841 if self.form == 'adp': 

842 self.mu[i] += self.adp_dipole( 

843 r[nearest][use], 

844 rvec[nearest][use], 

845 self.d[self.index[i], j_index], 

846 ) 

847 

848 self.lam[i] += self.adp_quadrupole( 

849 r[nearest][use], 

850 rvec[nearest][use], 

851 self.q[self.index[i], j_index], 

852 ) 

853 

854 # add in the electron embedding energy 

855 embedding_energy += self.embedded_energy[self.index[i]]( 

856 self.total_density[i] 

857 ) 

858 

859 components = dict(pair=pair_energy, embedding=embedding_energy) 

860 

861 if self.form == 'adp': 

862 mu_energy += np.sum(self.mu**2) / 2.0 

863 lam_energy += np.sum(self.lam**2) / 2.0 

864 

865 for i in range(len(atoms)): # this is the atom to be embedded 

866 trace_energy -= np.sum(self.lam[i].trace() ** 2) / 6.0 

867 

868 adp_result = dict( 

869 adp_mu=mu_energy, adp_lam=lam_energy, adp_trace=trace_energy 

870 ) 

871 components.update(adp_result) 

872 

873 self.positions = atoms.positions.copy() 

874 self.cell = atoms.get_cell().copy() 

875 

876 energy = 0.0 

877 for i in components: 

878 energy += components[i] 

879 

880 self.energy_free = energy 

881 self.energy_zero = energy 

882 

883 self.results['energy_components'] = components 

884 self.results['energy'] = energy 

885 self.results['free_energy'] = energy 

886 

887 def calculate_forces(self, atoms): 

888 # calculate the forces based on derivatives of the three EAM functions 

889 

890 self.update(atoms) 

891 self.results['forces'] = np.zeros((len(atoms), 3)) 

892 stresses = np.zeros((len(atoms), 3, 3)) 

893 

894 for i in range(len(atoms)): # this is the atom to be embedded 

895 neighbors, offsets = self.neighbors.get_neighbors(i) 

896 offset = np.dot(offsets, atoms.get_cell()) 

897 # create a vector of relative positions of neighbors 

898 rvec = atoms.positions[neighbors] + offset - atoms.positions[i] 

899 r = np.sqrt(np.sum(np.square(rvec), axis=1)) 

900 nearest = np.arange(len(r))[r < self.cutoff] 

901 

902 d_embedded_energy_i = self.d_embedded_energy[self.index[i]]( 

903 self.total_density[i] 

904 ) 

905 urvec = rvec.copy() # unit directional vector 

906 

907 for j in np.arange(len(neighbors)): 

908 urvec[j] = urvec[j] / r[j] 

909 

910 for j_index in range(self.Nelements): 

911 use = self.index[neighbors[nearest]] == j_index 

912 if not use.any(): 

913 continue 

914 rnuse = r[nearest][use] 

915 density_j = self.total_density[neighbors[nearest][use]] 

916 if self.form == 'fs': 

917 scale = ( 

918 self.d_phi[self.index[i], j_index](rnuse) 

919 + ( 

920 d_embedded_energy_i 

921 * self.d_electron_density[j_index, self.index[i]]( 

922 rnuse 

923 ) 

924 ) 

925 + ( 

926 self.d_embedded_energy[j_index](density_j) 

927 * self.d_electron_density[self.index[i], j_index]( 

928 rnuse 

929 ) 

930 ) 

931 ) 

932 else: 

933 scale = ( 

934 self.d_phi[self.index[i], j_index](rnuse) 

935 + ( 

936 d_embedded_energy_i 

937 * self.d_electron_density[j_index](rnuse) 

938 ) 

939 + ( 

940 self.d_embedded_energy[j_index](density_j) 

941 * self.d_electron_density[self.index[i]](rnuse) 

942 ) 

943 ) 

944 

945 self.results['forces'][i] += np.dot(scale, urvec[nearest][use]) 

946 stresses[i] += np.dot( 

947 (scale[:, np.newaxis] * urvec[nearest][use]).T, 

948 rvec[nearest][use], 

949 ) 

950 

951 if self.form == 'adp': 

952 adp_forces, adp_stresses = self.angular_forces( 

953 self.mu[i], 

954 self.mu[neighbors[nearest][use]], 

955 self.lam[i], 

956 self.lam[neighbors[nearest][use]], 

957 rnuse, 

958 rvec[nearest][use], 

959 self.index[i], 

960 j_index, 

961 ) 

962 

963 self.results['forces'][i] += adp_forces 

964 stresses[i] += adp_stresses 

965 

966 if self.atoms.cell.rank == 3: 

967 stress = 0.5 * np.sum(stresses, axis=0) / self.atoms.get_volume() 

968 self.results['stress'] = full_3x3_to_voigt_6_stress(stress) 

969 

970 def angular_forces(self, mu_i, mu, lam_i, lam, r, rvec, form1, form2): 

971 # calculate the extra components for the adp forces 

972 # rvec are the relative positions to atom i 

973 psi = np.zeros(mu.shape) 

974 for gamma in range(3): 

975 term1 = (mu_i[gamma] - mu[:, gamma]) * self.d[form1][form2](r) 

976 

977 term2 = np.sum( 

978 (mu_i - mu) 

979 * self.d_d[form1][form2](r)[:, np.newaxis] 

980 * (rvec * rvec[:, gamma][:, np.newaxis] / r[:, np.newaxis]), 

981 axis=1, 

982 ) 

983 

984 term3 = 2 * np.sum( 

985 (lam_i[:, gamma] + lam[:, :, gamma]) 

986 * rvec 

987 * self.q[form1][form2](r)[:, np.newaxis], 

988 axis=1, 

989 ) 

990 term4 = 0.0 

991 for alpha in range(3): 

992 for beta in range(3): 

993 rs = rvec[:, alpha] * rvec[:, beta] * rvec[:, gamma] 

994 term4 += ( 

995 (lam_i[alpha, beta] + lam[:, alpha, beta]) 

996 * self.d_q[form1][form2](r) 

997 * rs 

998 ) / r 

999 

1000 term5 = ( 

1001 (lam_i.trace() + lam.trace(axis1=1, axis2=2)) 

1002 * (self.d_q[form1][form2](r) * r + 2 * self.q[form1][form2](r)) 

1003 * rvec[:, gamma] 

1004 ) / 3.0 

1005 

1006 # the minus for term5 is a correction on the adp 

1007 # formulation given in the 2005 Mishin Paper and is posted 

1008 # on the NIST website with the AlH potential 

1009 psi[:, gamma] = term1 + term2 + term3 + term4 - term5 

1010 

1011 return np.sum(psi, axis=0), np.dot(psi.T, rvec) 

1012 

1013 def adp_dipole(self, r, rvec, d): 

1014 # calculate the dipole contribution 

1015 mu = np.sum((rvec * d(r)[:, np.newaxis]), axis=0) 

1016 

1017 return mu # sign to agree with lammps 

1018 

1019 def adp_quadrupole(self, r, rvec, q): 

1020 # slow way of calculating the quadrupole contribution 

1021 r = np.sqrt(np.sum(rvec**2, axis=1)) 

1022 

1023 lam = np.zeros([rvec.shape[0], 3, 3]) 

1024 qr = q(r) 

1025 for alpha in range(3): 

1026 for beta in range(3): 

1027 lam[:, alpha, beta] += qr * rvec[:, alpha] * rvec[:, beta] 

1028 

1029 return np.sum(lam, axis=0) 

1030 

1031 def deriv(self, spline): 

1032 """Wrapper for extracting the derivative from a spline""" 

1033 

1034 def d_spline(aspline): 

1035 return spline(aspline, 1) 

1036 

1037 return d_spline 

1038 

1039 def plot(self, name=''): 

1040 """Plot the individual curves""" 

1041 

1042 import matplotlib.pyplot as plt 

1043 

1044 if self.form == 'eam' or self.form == 'alloy' or self.form == 'fs': 

1045 nrow = 2 

1046 elif self.form == 'adp': 

1047 nrow = 3 

1048 else: 

1049 raise RuntimeError(f'Unknown form of potential: {self.form}') 

1050 

1051 if hasattr(self, 'r'): 

1052 r = self.r 

1053 else: 

1054 r = np.linspace(0, self.cutoff, 50) 

1055 

1056 if hasattr(self, 'rho'): 

1057 rho = self.rho 

1058 else: 

1059 rho = np.linspace(0, 10.0, 50) 

1060 

1061 plt.subplot(nrow, 2, 1) 

1062 self.elem_subplot( 

1063 rho, 

1064 self.embedded_energy, 

1065 r'$\rho$', 

1066 r'Embedding Energy $F(\bar\rho)$', 

1067 name, 

1068 plt, 

1069 ) 

1070 

1071 plt.subplot(nrow, 2, 2) 

1072 if self.form == 'fs': 

1073 self.multielem_subplot( 

1074 r, 

1075 self.electron_density, 

1076 r'$r$', 

1077 r'Electron Density $\rho(r)$', 

1078 name, 

1079 plt, 

1080 half=False, 

1081 ) 

1082 else: 

1083 self.elem_subplot( 

1084 r, 

1085 self.electron_density, 

1086 r'$r$', 

1087 r'Electron Density $\rho(r)$', 

1088 name, 

1089 plt, 

1090 ) 

1091 

1092 plt.subplot(nrow, 2, 3) 

1093 self.multielem_subplot( 

1094 r, self.phi, r'$r$', r'Pair Potential $\phi(r)$', name, plt 

1095 ) 

1096 plt.ylim(-1.0, 1.0) # need reasonable values 

1097 

1098 if self.form == 'adp': 

1099 plt.subplot(nrow, 2, 5) 

1100 self.multielem_subplot( 

1101 r, self.d, r'$r$', r'Dipole Energy', name, plt 

1102 ) 

1103 

1104 plt.subplot(nrow, 2, 6) 

1105 self.multielem_subplot( 

1106 r, self.q, r'$r$', r'Quadrupole Energy', name, plt 

1107 ) 

1108 

1109 plt.plot() 

1110 

1111 def elem_subplot(self, curvex, curvey, xlabel, ylabel, name, plt): 

1112 plt.xlabel(xlabel) 

1113 plt.ylabel(ylabel) 

1114 for i in np.arange(self.Nelements): 

1115 label = name + ' ' + self.elements[i] 

1116 plt.plot(curvex, curvey[i](curvex), label=label) 

1117 plt.legend() 

1118 

1119 def multielem_subplot( 

1120 self, curvex, curvey, xlabel, ylabel, name, plt, half=True 

1121 ): 

1122 plt.xlabel(xlabel) 

1123 plt.ylabel(ylabel) 

1124 for i in np.arange(self.Nelements): 

1125 for j in np.arange((i + 1) if half else self.Nelements): 

1126 label = name + ' ' + self.elements[i] + '-' + self.elements[j] 

1127 plt.plot(curvex, curvey[i, j](curvex), label=label) 

1128 plt.legend()