Coverage for ase/eos.py: 77.16%
197 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
1import warnings
3import numpy as np
5from ase.units import kJ
7eos_names = [
8 'sj',
9 'taylor',
10 'murnaghan',
11 'birch',
12 'birchmurnaghan',
13 'pouriertarantola',
14 'vinet',
15 'anton-schmidt',
16 'p3',
17]
20def taylor(V, E0, beta, alpha, V0):
21 "Taylor Expansion up to 3rd order about V0"
23 E = E0 + beta / 2 * (V - V0) ** 2 / V0 + alpha / 6 * (V - V0) ** 3 / V0
24 return E
27def murnaghan(V, E0, B0, BP, V0):
28 "From PRB 28,5480 (1983"
30 E = (
31 E0
32 + B0 * V / BP * (((V0 / V) ** BP) / (BP - 1) + 1)
33 - V0 * B0 / (BP - 1)
34 )
35 return E
38def birch(V, E0, B0, BP, V0):
39 """
40 From Intermetallic compounds: Principles and Practice, Vol. I: Principles
41 Chapter 9 pages 195-210 by M. Mehl. B. Klein, D. Papaconstantopoulos
42 paper downloaded from Web
44 case where n=0
45 """
47 E = (
48 E0
49 + 9 / 8 * B0 * V0 * ((V0 / V) ** (2 / 3) - 1) ** 2
50 + 9 / 16 * B0 * V0 * (BP - 4) * ((V0 / V) ** (2 / 3) - 1) ** 3
51 )
52 return E
55def birchmurnaghan(V, E0, B0, BP, V0):
56 """
57 BirchMurnaghan equation from PRB 70, 224107
58 Eq. (3) in the paper. Note that there's a typo in the paper and it uses
59 inversed expression for eta.
60 """
62 eta = (V0 / V) ** (1 / 3)
63 E = E0 + 9 * B0 * V0 / 16 * (eta**2 - 1) ** 2 * (
64 6 + BP * (eta**2 - 1) - 4 * eta**2
65 )
66 return E
69def check_birchmurnaghan():
70 from sympy import Rational, diff, simplify, symbols
72 v, b, bp, v0 = symbols('v b bp v0')
73 x = (v0 / v) ** Rational(2, 3)
74 e = 9 * b * v0 * (x - 1) ** 2 * (6 + bp * (x - 1) - 4 * x) / 16
75 print(e)
76 B = diff(e, v, 2) * v
77 BP = -v * diff(B, v) / b
78 print(simplify(B.subs(v, v0)))
79 print(simplify(BP.subs(v, v0)))
82def pouriertarantola(V, E0, B0, BP, V0):
83 "Pourier-Tarantola equation from PRB 70, 224107"
85 eta = (V / V0) ** (1 / 3)
86 squiggle = -3 * np.log(eta)
88 E = E0 + B0 * V0 * squiggle**2 / 6 * (3 + squiggle * (BP - 2))
89 return E
92def vinet(V, E0, B0, BP, V0):
93 "Vinet equation from PRB 70, 224107"
95 eta = (V / V0) ** (1 / 3)
97 E = E0 + 2 * B0 * V0 / (BP - 1) ** 2 * (
98 2
99 - (5 + 3 * BP * (eta - 1) - 3 * eta)
100 * np.exp(-3 * (BP - 1) * (eta - 1) / 2)
101 )
102 return E
105def anton_schmidt(
106 v: np.ndarray,
107 e0: float,
108 b0: float,
109 bp0: float,
110 v0: float,
111) -> np.ndarray:
112 r"""Anton-Schmidt EOS [1]_.
114 In the original formula, :math:`E_\infty` (energy at infinite separation)
115 is a parameter, which is given by [1]_
117 .. math:: E_\infty = E_0 + \frac{B_0 V_0}{(n + 1)^2}.
119 :math:`n` is related to the Grüneisen parameter [1]_ as
121 .. math:: n = -1/6 - \gamma.
123 Taking the Grüneisen parameters in Ref. [2]_, :math:`n` should be about -2.
125 :math:`n` is also given with :math:`B'_{0}` by [3]_:
127 .. math:: n = -\\frac{1}{2} B'_{0}.
129 References
130 ----------
131 .. [1] H. Anton and P. C. Schmidt, Intermetallics 5, 449 (1997).
132 :doi:`10.1016/s0966-9795(97)00017-4`
133 .. [2] B. Mayer, H. Anton, E. Bott, M. Methfessel, J. Sticht, J. Harris,
134 and P. C. Schmidt, Intermetallics 11, 23 (2003).
135 :doi:`10.1016/s0966-9795(02)00127-9`
136 .. [3] A. Otero-de-la-Roza and V. Luaña,
137 Comput. Phys. Commun. 182, 1708 (2011).
138 :doi:`10.1016/j.cpc.2011.04.016`
140 """
141 n = -0.5 * bp0
142 e_infinity = e0 + b0 * v0 / (n + 1) ** 2
143 e = b0 * v0 / (n + 1) * (v / v0) ** (n + 1) * (np.log(v / v0) - 1 / (n + 1))
144 return e + e_infinity
147def p3(V, c0, c1, c2, c3):
148 "polynomial fit"
150 E = c0 + c1 * V + c2 * V**2 + c3 * V**3
151 return E
154def parabola(x, a, b, c):
155 """parabola polynomial function
157 this function is used to fit the data to get good guesses for
158 the equation of state fits
160 a 4th order polynomial fit to get good guesses for
161 was not a good idea because for noisy data the fit is too wiggly
162 2nd order seems to be sufficient, and guarantees a single minimum"""
164 return a + b * x + c * x**2
167class EquationOfState:
168 """Fit equation of state for bulk systems.
170 Parameters
171 ----------
172 eos : str
173 Name of the equation of state to fit. Must be one of:
175 - ``sj`` (default)
176 A third order inverse polynomial fit 10.1103/PhysRevB.67.026103
178 ::
180 2 3 -1/3
181 E(V) = c + c t + c t + c t , t = V
182 0 1 2 3
184 - ``taylor``
185 A third order Taylor series expansion about the minimum volume
187 - ``murnaghan``
188 PRB 28, 5480 (1983)
190 - ``birch``
191 Intermetallic compounds: Principles and Practice,
192 Vol I: Principles. pages 195-210
194 - ``birchmurnaghan``
195 PRB 70, 224107
197 - ``pouriertarantola``
198 PRB 70, 224107
200 - ``vinet``
201 PRB 70, 224107
203 - ``anton-schmidt``
204 H. Anton and P. C. Schmidt, Intermetallics 5, 449 (1997).
205 :doi:`10.1016/s0966-9795(97)00017-4`
207 - ``p3``
208 A third order polynomial fit
210 Examples
211 --------
212 >>> from ase.build import bulk
213 >>> from ase.calculators.emt import EMT
214 >>> import numpy as np
215 >>> from ase.eos import EquationOfState
216 >>> atoms = bulk('Al')
217 >>> atoms.calc = EMT()
218 >>> cell = atoms.cell.copy()
219 >>> volumes = []
220 >>> energies = []
221 >>> for x in np.linspace(0.97, 1.01, 5):
222 ... atoms.set_cell(cell * x, scale_atoms=True)
223 ... volumes.append(atoms.get_volume())
224 ... energies.append(atoms.get_potential_energy())
225 >>> eos = EquationOfState(volumes, energies, eos='murnaghan')
226 >>> v0, e0, b0 = eos.fit()
227 >>> ax = eos.plot(show=False)
229 """
231 def __init__(self, volumes, energies, eos='sj'):
232 self.v = np.array(volumes)
233 self.e = np.array(energies)
235 old2new = {
236 'sjeos': 'sj',
237 'antonschmidt': 'anton-schmidt',
238 }
239 for old_name, new_name in old2new.items():
240 if eos == old_name:
241 eos = new_name
242 msg = (
243 f'`{old_name}` is an old EOS name. '
244 f'Use `{new_name}` instead. '
245 'The old EOS names will be removed in ASE 3.30.0.'
246 )
247 warnings.warn(msg, FutureWarning)
248 self.eos_string = eos
249 self.v0 = None
251 def fit(self, warn=True):
252 """Calculate volume, energy, and bulk modulus.
254 Returns the optimal volume, the minimum energy, and the bulk
255 modulus. Notice that the ASE units for the bulk modulus is
256 eV/Angstrom^3 - to get the value in GPa, do this::
258 v0, e0, B = eos.fit()
259 print(B / kJ * 1.0e24, 'GPa')
261 """
262 from scipy.optimize import curve_fit
264 if self.eos_string == 'sj':
265 return self.fit_sjeos()
267 self.func = globals()[self.eos_string.replace('-', '_')]
269 p0 = [min(self.e), 1, 1]
270 popt, _pcov = curve_fit(parabola, self.v, self.e, p0)
272 parabola_parameters = popt
273 # Here I just make sure the minimum is bracketed by the volumes
274 # this if for the solver
275 minvol = min(self.v)
276 maxvol = max(self.v)
278 # the minimum of the parabola is at dE/dV = 0, or 2 * c V +b =0
279 c = parabola_parameters[2]
280 b = parabola_parameters[1]
281 a = parabola_parameters[0]
282 parabola_vmin = -b / 2 / c
284 # evaluate the parabola at the minimum to estimate the groundstate
285 # energy
286 E0 = parabola(parabola_vmin, a, b, c)
287 # estimate the bulk modulus from Vo * E''. E'' = 2 * c
288 B0 = 2 * c * parabola_vmin
290 # (∂B/∂P)_V0 = (∂B/∂V)_V0 / (∂P/∂V)_V0 (4.0 for the 2nd-order BM)
291 bp0 = 4.0
293 initial_guess = [E0, B0, bp0, parabola_vmin]
295 # now fit the equation of state
296 p0 = initial_guess
297 popt, _pcov = curve_fit(self.func, self.v, self.e, p0)
299 self.eos_parameters = popt
301 if self.eos_string == 'p3':
302 c0, c1, c2, c3 = self.eos_parameters
303 # find minimum E in E = c0 + c1 * V + c2 * V**2 + c3 * V**3
304 # dE/dV = c1+ 2 * c2 * V + 3 * c3 * V**2 = 0
305 # solve by quadratic formula with the positive root
307 a = 3 * c3
308 b = 2 * c2
309 c = c1
311 self.v0 = (-b + np.sqrt(b**2 - 4 * a * c)) / (2 * a)
312 self.e0 = p3(self.v0, c0, c1, c2, c3)
313 self.B = (2 * c2 + 6 * c3 * self.v0) * self.v0
314 else:
315 self.v0 = self.eos_parameters[3]
316 self.e0 = self.eos_parameters[0]
317 self.B = self.eos_parameters[1]
319 if warn and not (minvol < self.v0 < maxvol):
320 warnings.warn(
321 'The minimum volume of your fit is not in '
322 'your volumes. You may not have a minimum in your dataset!'
323 )
325 return self.v0, self.e0, self.B
327 def getplotdata(self):
328 if self.v0 is None:
329 self.fit()
331 x = np.linspace(min(self.v), max(self.v), 100)
332 if self.eos_string == 'sj':
333 y = self.fit0(x ** -(1 / 3))
334 else:
335 y = self.func(x, *self.eos_parameters)
337 return self.eos_string, self.e0, self.v0, self.B, x, y, self.v, self.e
339 def plot(self, filename=None, show=False, ax=None):
340 """Plot fitted energy curve.
342 Uses Matplotlib to plot the energy curve. Use *show=True* to
343 show the figure and *filename='abc.png'* or
344 *filename='abc.eps'* to save the figure to a file."""
346 import matplotlib.pyplot as plt
348 plotdata = self.getplotdata()
350 ax = plot(*plotdata, ax=ax)
352 if show:
353 plt.show()
354 if filename is not None:
355 fig = ax.get_figure()
356 fig.savefig(filename)
357 return ax
359 def fit_sjeos(self):
360 """Calculate volume, energy, and bulk modulus.
362 Returns the optimal volume, the minimum energy, and the bulk
363 modulus. Notice that the ASE units for the bulk modulus is
364 eV/Angstrom^3 - to get the value in GPa, do this::
366 v0, e0, B = eos.fit()
367 print(B / kJ * 1.0e24, 'GPa')
369 """
371 fit0 = np.poly1d(np.polyfit(self.v ** -(1 / 3), self.e, 3))
372 fit1 = np.polyder(fit0, 1)
373 fit2 = np.polyder(fit1, 1)
375 self.v0 = None
376 for t in np.roots(fit1):
377 if isinstance(t, float) and t > 0 and fit2(t) > 0:
378 self.v0 = t**-3
379 break
381 if self.v0 is None:
382 raise ValueError('No minimum!')
384 self.e0 = fit0(t)
385 self.B = t**5 * fit2(t) / 9
386 self.fit0 = fit0
388 return self.v0, self.e0, self.B
391def plot(eos_string, e0, v0, B, x, y, v, e, ax=None):
392 if ax is None:
393 import matplotlib.pyplot as plt
395 ax = plt.gca()
397 ax.plot(x, y, ls='-', color='C3') # By default red line
398 ax.plot(
399 v, e, ls='', marker='o', mec='C0', mfc='C0'
400 ) # By default blue marker
402 try:
403 ax.set_xlabel('volume [Å$^3$]')
404 ax.set_ylabel('energy [eV]')
405 ax.set_title(
406 '%s: E: %.3f eV, V: %.3f Å$^3$, B: %.3f GPa'
407 % (eos_string, e0, v0, B / kJ * 1.0e24)
408 )
410 except ImportError: # XXX what would cause this error? LaTeX?
411 warnings.warn('Could not use LaTeX formatting')
412 ax.set_xlabel('volume [L(length)^3]')
413 ax.set_ylabel('energy [E(energy)]')
414 ax.set_title(
415 '%s: E: %.3f E, V: %.3f L^3, B: %.3e E/L^3'
416 % (eos_string, e0, v0, B)
417 )
419 return ax
422def calculate_eos(atoms, npoints=5, eps=0.04, trajectory=None, callback=None):
423 """Calculate equation-of-state.
425 atoms: Atoms object
426 System to calculate EOS for. Must have a calculator attached.
427 npoints: int
428 Number of points.
429 eps: float
430 Variation in volume from v0*(1-eps) to v0*(1+eps).
431 trajectory: Trjectory object or str
432 Write configurations to a trajectory file.
433 callback: function
434 Called after every energy calculation.
436 >>> from ase.build import bulk
437 >>> from ase.calculators.emt import EMT
438 >>> from ase.eos import calculate_eos
440 >>> a = bulk('Cu', 'fcc', a=3.6)
441 >>> a.calc = EMT()
442 >>> eos = calculate_eos(a, trajectory='Cu.traj')
443 >>> v, e, B = eos.fit()
444 >>> a = (4 * v)**(1 / 3.0)
445 >>> print('{0:.6f}'.format(a))
446 3.589825
447 """
449 # Save original positions and cell:
450 p0 = atoms.get_positions()
451 c0 = atoms.get_cell()
453 if isinstance(trajectory, str):
454 from ase.io import Trajectory
456 trajectory = Trajectory(trajectory, 'w', atoms)
458 if trajectory is not None:
459 trajectory.set_description(
460 {'type': 'eos', 'npoints': npoints, 'eps': eps}
461 )
463 try:
464 energies = []
465 volumes = []
466 for x in np.linspace(1 - eps, 1 + eps, npoints) ** (1 / 3):
467 atoms.set_cell(x * c0, scale_atoms=True)
468 volumes.append(atoms.get_volume())
469 energies.append(atoms.get_potential_energy())
470 if callback:
471 callback()
472 if trajectory is not None:
473 trajectory.write()
474 return EquationOfState(volumes, energies)
475 finally:
476 atoms.cell = c0
477 atoms.positions = p0
478 if trajectory is not None:
479 trajectory.close()
482class CLICommand:
483 """Calculate EOS from one or more trajectory files.
485 See :ref:`eos_example` for more information.
486 """
488 @staticmethod
489 def add_arguments(parser):
490 parser.add_argument('trajectories', nargs='+', metavar='trajectory')
491 parser.add_argument(
492 '-p',
493 '--plot',
494 action='store_true',
495 help='Plot EOS fit. Default behaviour is to write results of fit.',
496 )
497 parser.add_argument(
498 '-t',
499 '--type',
500 default='sj',
501 help='Type of fit. Must be one of {}.'.format(
502 ', '.join(eos_names)
503 ),
504 )
506 @staticmethod
507 def run(args):
508 from ase.io import read
510 if not args.plot:
511 print(
512 '# filename '
513 'points volume energy bulk modulus'
514 )
515 print(
516 '# '
517 ' [Ang^3] [eV] [GPa]'
518 )
519 for name in args.trajectories:
520 if name == '-':
521 # Special case - used by ASE's GUI:
522 import pickle
523 import sys
525 v, e = pickle.load(sys.stdin.buffer)
526 else:
527 if '@' in name:
528 index = None
529 else:
530 index = ':'
531 images = read(name, index=index)
532 v = [atoms.get_volume() for atoms in images]
533 e = [atoms.get_potential_energy() for atoms in images]
534 eos = EquationOfState(v, e, args.type)
535 if args.plot:
536 eos.plot()
537 else:
538 try:
539 v0, e0, B = eos.fit()
540 except ValueError as ex:
541 print('{:30}{:2} {}'.format(name, len(v), ex.message))
542 else:
543 print(
544 '{:30}{:2} {:10.3f}{:10.3f}{:14.3f}'.format(
545 name, len(v), v0, e0, B / kJ * 1.0e24
546 )
547 )