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
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""Calculator for the Embedded Atom Method Potential"""
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
10import os
12import numpy as np
13from scipy.interpolate import InterpolatedUnivariateSpline as spline
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
22class EAM(Calculator):
23 r"""EAM Interface Documentation
25 Introduction
26 ============
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.
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/
42 Theory
43 ======
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.
52 The total energy :math:`E_{\rm tot}` of an arbitrary arrangement of atoms is
53 given by the EAM potential as
55 .. math::
56 E_\text{tot} =
57 \sum_i F(\bar\rho_i) + \frac{1}{2}\sum_{i\ne j} \phi(r_{ij})
59 and
61 .. math::
62 \bar\rho_i = \sum_j \rho(r_{ij})
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.
72 The ADP potential is defined as
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
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}`.
86 The fs potential is defined as
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})
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.
97 Running the Calculator
98 ======================
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.
108 For example::
110 from ase.calculators.eam import EAM
112 mishin = EAM(potential='Al99.eam.alloy')
113 mishin.write_potential('new.eam.alloy')
114 mishin.plot()
116 slab.calc = mishin
117 slab.get_potential_energy()
118 slab.get_forces()
119 slab.get_stress()
121 The breakdown of energy contribution from the indvidual components are
122 stored in the calculator instance ``.results['energy_components']``
124 Arguments:
125 ==========
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
137 ``elements[N]`` array of N element abbreviations
139 ``embedded_energy[N]`` arrays of embedded energy functions
141 ``electron_density[N]`` arrays of electron density functions
143 ``phi[N,N]`` arrays of pair potential functions
145 ``d_embedded_energy[N]`` arrays of derivative embedded energy functions
147 ``d_electron_density[N]`` arrays of derivative electron density functions
149 ``d_phi[N,N]`` arrays of derivative pair potentials functions
151 ``d[N,N], q[N,N]`` ADP dipole and quadrupole function
153 ``d_d[N,N], d_q[N,N]`` ADP dipole and quadrupole derivative functions
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.
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
168 ========================= ================================================
171 Additional parameters for writing potential files
172 =================================================
174 The following parameters are only required for writing a potential in
175 ``.alloy``, ``.adp`` or ``fs`` format file.
177 ========================= ================================================
178 Keyword Description
179 ========================= ================================================
180 ``header`` Three line text header. Default is standard
181 message.
183 ``Z[N]`` Array of atomic number of each element
185 ``mass[N]`` Atomic mass of each element
187 ``a[N]`` Array of lattice parameters for each element
189 ``lattice[N]`` Lattice type
191 ``nrho`` No. of rho samples along embedded energy curve
193 ``drho`` Increment for sampling density
195 ``nr`` No. of radial points along density and pair
196 potential curves
198 ``dr`` Increment for sampling radius
200 ========================= ================================================
202 Special features
203 ================
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.
210 Notes/Issues
211 ============
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.
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.
223 * Any supplied values will override values read from the file.
225 * The derivative functions, if supplied, are only used to calculate
226 forces.
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.
232 .. _LAMMPS: https://www.lammps.org/
234 .. [1] M.S. Daw and M.I. Baskes, Phys. Rev. Letters 50 (1983)
235 1285.
237 .. [2] Y. Mishin, M.J. Mehl, and D.A. Papaconstantopoulos,
238 Acta Materialia 53 2005 4029--4041.
239 """
241 implemented_properties = ['energy', 'free_energy', 'forces', 'stress']
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 )
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 ):
263 self.form = form
265 if 'potential' in kwargs:
266 self.read_potential(kwargs['potential'])
268 Calculator.__init__(
269 self, restart, ignore_bad_restart_file, label, atoms, **kwargs
270 )
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 )
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 )
311 def set_form(self, name):
312 """set the form variable based on the file name suffix"""
313 extension = os.path.splitext(name)[1]
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}')
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 """
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)
338 def _read_potential(self, fd):
339 if self.form is None:
340 self.set_form(fd.name)
342 lines = fd.readlines()
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
351 if self.form == 'eam': # single element eam file (aka funcfl)
352 self.header = lines[:1]
354 data = lines_to_list(lines[1:])
356 # eam form is just like an alloy form for one element
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]]
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])
371 n = 9 + self.nrho
372 self.embedded_data = np.array([np.float64(data[9:n])])
374 self.rphi_data = np.zeros([self.Nelements, self.Nelements, self.nr])
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)
381 self.density_data = np.array(
382 [np.float64(data[n + self.nr : n + 2 * self.nr])]
383 )
385 elif self.form in ['alloy', 'adp']:
386 self.header = lines[:3]
387 i = 3
389 data = lines_to_list(lines[i:])
391 self.Nelements = int(data[0])
392 d = 1
393 self.elements = data[d : d + self.Nelements]
394 d += self.Nelements
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])
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
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
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
423 # reads in the r*phi data for each interaction between elements
424 self.rphi_data = np.zeros([self.Nelements, self.Nelements, self.nr])
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
431 elif self.form == 'fs':
432 self.header = lines[:3]
433 i = 3
435 data = lines_to_list(lines[i:])
437 self.Nelements = int(data[0])
438 d = 1
439 self.elements = data[d : d + self.Nelements]
440 d += self.Nelements
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])
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
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
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
473 # reads in the r*phi data for each interaction between elements
474 self.rphi_data = np.zeros([self.Nelements, self.Nelements, self.nr])
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
481 self.r = np.arange(0, self.nr) * self.dr
482 self.rho = np.arange(0, self.nrho) * self.drho
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()
490 if self.form == 'adp':
491 self.read_adp_data(data, d)
492 self.set_adp_splines()
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)
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])
510 self.phi = np.empty([self.Nelements, self.Nelements], object)
511 self.d_phi = np.empty([self.Nelements, self.Nelements], object)
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 )
521 self.d_phi[i, j] = self.deriv(self.phi[i, j])
523 if j != i:
524 self.phi[j, i] = self.phi[i, j]
525 self.d_phi[j, i] = self.d_phi[i, j]
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 )
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 )
550 self.phi = np.empty([self.Nelements, self.Nelements], object)
551 self.d_phi = np.empty([self.Nelements, self.Nelements], object)
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 )
559 self.d_phi[i, j] = self.deriv(self.phi[i, j])
561 if j != i:
562 self.phi[j, i] = self.phi[i, j]
563 self.d_phi[j, i] = self.d_phi[i, j]
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)
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])
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]
585 def read_adp_data(self, data, d):
586 """read in the extra adp data from the potential file"""
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
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
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 """
608 with open(filename, 'wb') as fd:
609 self._write_potential(fd, nc=nc, numformat=numformat)
611 def _write_potential(self, fd, nc, numformat):
612 assert self.nr % nc == 0
613 assert self.nrho % nc == 0
615 if self.form == 'eam':
616 return self._write_potential_eam(fd, nc, numformat)
618 for i in range(3):
619 fd.write(self.header[i].encode())
621 fd.write(f'{self.Nelements} '.encode())
622 fd.write(' '.join(self.elements).encode() + b'\n')
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 )
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)
635 rs = np.arange(0, self.nr) * self.dr
636 rhos = np.arange(0, self.nrho) * self.drho
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 )
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 )
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])
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])
687 def _write_potential_eam(self, fd, nc, numformat):
688 """Write the potential in the DYNAMO single-element funcfl format."""
690 fd.write(self.header[0].encode())
692 i = 0 # The DYNAMO funcfl format can store only one element.
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())
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())
701 rs = np.arange(0, self.nr) * self.dr
702 rhos = np.arange(0, self.nrho) * self.drho
704 arr = self.embedded_energy[i](rhos).reshape(self.nrho // nc, nc)
705 np.savetxt(fd, arr, fmt=nc * [numformat])
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])
712 arr = self.electron_density[i](rs).reshape(self.nr // nc, nc)
713 np.savetxt(fd, arr, fmt=nc * [numformat])
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 )
723 if np.any(unavailable):
724 raise RuntimeError(
725 'These elements are not in the potential: '
726 f'{elements[unavailable]}'
727 )
729 # cutoffs need to be a vector for NeighborList
730 cutoffs = self.cutoff * np.ones(len(atoms))
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()
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)
750 def calculate(
751 self, atoms=None, properties=None, system_changes=all_changes
752 ):
753 """EAM Calculator
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 """
766 if properties is None:
767 properties = ['energy']
768 Calculator.calculate(self, atoms, properties, system_changes)
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)
775 if 'forces' in properties or 'stress' in properties:
776 self.calculate_forces(self.atoms)
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)
784 if property in ['forces', 'stress']:
785 self.calculate_forces(self.atoms)
787 # we need to remember the previous state of parameters
789 # if 'potential' in parameter_changes and potential != None:
790 # self.read_potential(potential)
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 """
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
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])
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())
814 rvec = atoms.positions[neighbors] + offset - atoms.positions[i]
816 # calculate the distance to the nearest neighbors
817 r = np.sqrt(np.sum(np.square(rvec), axis=1))
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 )
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
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 )
848 self.lam[i] += self.adp_quadrupole(
849 r[nearest][use],
850 rvec[nearest][use],
851 self.q[self.index[i], j_index],
852 )
854 # add in the electron embedding energy
855 embedding_energy += self.embedded_energy[self.index[i]](
856 self.total_density[i]
857 )
859 components = dict(pair=pair_energy, embedding=embedding_energy)
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
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
868 adp_result = dict(
869 adp_mu=mu_energy, adp_lam=lam_energy, adp_trace=trace_energy
870 )
871 components.update(adp_result)
873 self.positions = atoms.positions.copy()
874 self.cell = atoms.get_cell().copy()
876 energy = 0.0
877 for i in components:
878 energy += components[i]
880 self.energy_free = energy
881 self.energy_zero = energy
883 self.results['energy_components'] = components
884 self.results['energy'] = energy
885 self.results['free_energy'] = energy
887 def calculate_forces(self, atoms):
888 # calculate the forces based on derivatives of the three EAM functions
890 self.update(atoms)
891 self.results['forces'] = np.zeros((len(atoms), 3))
892 stresses = np.zeros((len(atoms), 3, 3))
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]
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
907 for j in np.arange(len(neighbors)):
908 urvec[j] = urvec[j] / r[j]
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 )
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 )
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 )
963 self.results['forces'][i] += adp_forces
964 stresses[i] += adp_stresses
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)
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)
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 )
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
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
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
1011 return np.sum(psi, axis=0), np.dot(psi.T, rvec)
1013 def adp_dipole(self, r, rvec, d):
1014 # calculate the dipole contribution
1015 mu = np.sum((rvec * d(r)[:, np.newaxis]), axis=0)
1017 return mu # sign to agree with lammps
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))
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]
1029 return np.sum(lam, axis=0)
1031 def deriv(self, spline):
1032 """Wrapper for extracting the derivative from a spline"""
1034 def d_spline(aspline):
1035 return spline(aspline, 1)
1037 return d_spline
1039 def plot(self, name=''):
1040 """Plot the individual curves"""
1042 import matplotlib.pyplot as plt
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}')
1051 if hasattr(self, 'r'):
1052 r = self.r
1053 else:
1054 r = np.linspace(0, self.cutoff, 50)
1056 if hasattr(self, 'rho'):
1057 rho = self.rho
1058 else:
1059 rho = np.linspace(0, 10.0, 50)
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 )
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 )
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
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 )
1104 plt.subplot(nrow, 2, 6)
1105 self.multielem_subplot(
1106 r, self.q, r'$r$', r'Quadrupole Energy', name, plt
1107 )
1109 plt.plot()
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()
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()