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

1import warnings 

2 

3import numpy as np 

4 

5from ase.units import kJ 

6 

7eos_names = [ 

8 'sj', 

9 'taylor', 

10 'murnaghan', 

11 'birch', 

12 'birchmurnaghan', 

13 'pouriertarantola', 

14 'vinet', 

15 'anton-schmidt', 

16 'p3', 

17] 

18 

19 

20def taylor(V, E0, beta, alpha, V0): 

21 "Taylor Expansion up to 3rd order about V0" 

22 

23 E = E0 + beta / 2 * (V - V0) ** 2 / V0 + alpha / 6 * (V - V0) ** 3 / V0 

24 return E 

25 

26 

27def murnaghan(V, E0, B0, BP, V0): 

28 "From PRB 28,5480 (1983" 

29 

30 E = ( 

31 E0 

32 + B0 * V / BP * (((V0 / V) ** BP) / (BP - 1) + 1) 

33 - V0 * B0 / (BP - 1) 

34 ) 

35 return E 

36 

37 

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 

43 

44 case where n=0 

45 """ 

46 

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 

53 

54 

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 """ 

61 

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 

67 

68 

69def check_birchmurnaghan(): 

70 from sympy import Rational, diff, simplify, symbols 

71 

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))) 

80 

81 

82def pouriertarantola(V, E0, B0, BP, V0): 

83 "Pourier-Tarantola equation from PRB 70, 224107" 

84 

85 eta = (V / V0) ** (1 / 3) 

86 squiggle = -3 * np.log(eta) 

87 

88 E = E0 + B0 * V0 * squiggle**2 / 6 * (3 + squiggle * (BP - 2)) 

89 return E 

90 

91 

92def vinet(V, E0, B0, BP, V0): 

93 "Vinet equation from PRB 70, 224107" 

94 

95 eta = (V / V0) ** (1 / 3) 

96 

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 

103 

104 

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]_. 

113 

114 In the original formula, :math:`E_\infty` (energy at infinite separation) 

115 is a parameter, which is given by [1]_ 

116 

117 .. math:: E_\infty = E_0 + \frac{B_0 V_0}{(n + 1)^2}. 

118 

119 :math:`n` is related to the Grüneisen parameter [1]_ as 

120 

121 .. math:: n = -1/6 - \gamma. 

122 

123 Taking the Grüneisen parameters in Ref. [2]_, :math:`n` should be about -2. 

124 

125 :math:`n` is also given with :math:`B'_{0}` by [3]_: 

126 

127 .. math:: n = -\\frac{1}{2} B'_{0}. 

128 

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` 

139 

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 

145 

146 

147def p3(V, c0, c1, c2, c3): 

148 "polynomial fit" 

149 

150 E = c0 + c1 * V + c2 * V**2 + c3 * V**3 

151 return E 

152 

153 

154def parabola(x, a, b, c): 

155 """parabola polynomial function 

156 

157 this function is used to fit the data to get good guesses for 

158 the equation of state fits 

159 

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""" 

163 

164 return a + b * x + c * x**2 

165 

166 

167class EquationOfState: 

168 """Fit equation of state for bulk systems. 

169 

170 Parameters 

171 ---------- 

172 eos : str 

173 Name of the equation of state to fit. Must be one of: 

174 

175 - ``sj`` (default) 

176 A third order inverse polynomial fit 10.1103/PhysRevB.67.026103 

177 

178 :: 

179 

180 2 3 -1/3 

181 E(V) = c + c t + c t + c t , t = V 

182 0 1 2 3 

183 

184 - ``taylor`` 

185 A third order Taylor series expansion about the minimum volume 

186 

187 - ``murnaghan`` 

188 PRB 28, 5480 (1983) 

189 

190 - ``birch`` 

191 Intermetallic compounds: Principles and Practice, 

192 Vol I: Principles. pages 195-210 

193 

194 - ``birchmurnaghan`` 

195 PRB 70, 224107 

196 

197 - ``pouriertarantola`` 

198 PRB 70, 224107 

199 

200 - ``vinet`` 

201 PRB 70, 224107 

202 

203 - ``anton-schmidt`` 

204 H. Anton and P. C. Schmidt, Intermetallics 5, 449 (1997). 

205 :doi:`10.1016/s0966-9795(97)00017-4` 

206 

207 - ``p3`` 

208 A third order polynomial fit 

209 

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) 

228 

229 """ 

230 

231 def __init__(self, volumes, energies, eos='sj'): 

232 self.v = np.array(volumes) 

233 self.e = np.array(energies) 

234 

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 

250 

251 def fit(self, warn=True): 

252 """Calculate volume, energy, and bulk modulus. 

253 

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:: 

257 

258 v0, e0, B = eos.fit() 

259 print(B / kJ * 1.0e24, 'GPa') 

260 

261 """ 

262 from scipy.optimize import curve_fit 

263 

264 if self.eos_string == 'sj': 

265 return self.fit_sjeos() 

266 

267 self.func = globals()[self.eos_string.replace('-', '_')] 

268 

269 p0 = [min(self.e), 1, 1] 

270 popt, _pcov = curve_fit(parabola, self.v, self.e, p0) 

271 

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) 

277 

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 

283 

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 

289 

290 # (∂B/∂P)_V0 = (∂B/∂V)_V0 / (∂P/∂V)_V0 (4.0 for the 2nd-order BM) 

291 bp0 = 4.0 

292 

293 initial_guess = [E0, B0, bp0, parabola_vmin] 

294 

295 # now fit the equation of state 

296 p0 = initial_guess 

297 popt, _pcov = curve_fit(self.func, self.v, self.e, p0) 

298 

299 self.eos_parameters = popt 

300 

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 

306 

307 a = 3 * c3 

308 b = 2 * c2 

309 c = c1 

310 

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] 

318 

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 ) 

324 

325 return self.v0, self.e0, self.B 

326 

327 def getplotdata(self): 

328 if self.v0 is None: 

329 self.fit() 

330 

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) 

336 

337 return self.eos_string, self.e0, self.v0, self.B, x, y, self.v, self.e 

338 

339 def plot(self, filename=None, show=False, ax=None): 

340 """Plot fitted energy curve. 

341 

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.""" 

345 

346 import matplotlib.pyplot as plt 

347 

348 plotdata = self.getplotdata() 

349 

350 ax = plot(*plotdata, ax=ax) 

351 

352 if show: 

353 plt.show() 

354 if filename is not None: 

355 fig = ax.get_figure() 

356 fig.savefig(filename) 

357 return ax 

358 

359 def fit_sjeos(self): 

360 """Calculate volume, energy, and bulk modulus. 

361 

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:: 

365 

366 v0, e0, B = eos.fit() 

367 print(B / kJ * 1.0e24, 'GPa') 

368 

369 """ 

370 

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) 

374 

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 

380 

381 if self.v0 is None: 

382 raise ValueError('No minimum!') 

383 

384 self.e0 = fit0(t) 

385 self.B = t**5 * fit2(t) / 9 

386 self.fit0 = fit0 

387 

388 return self.v0, self.e0, self.B 

389 

390 

391def plot(eos_string, e0, v0, B, x, y, v, e, ax=None): 

392 if ax is None: 

393 import matplotlib.pyplot as plt 

394 

395 ax = plt.gca() 

396 

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 

401 

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 ) 

409 

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 ) 

418 

419 return ax 

420 

421 

422def calculate_eos(atoms, npoints=5, eps=0.04, trajectory=None, callback=None): 

423 """Calculate equation-of-state. 

424 

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. 

435 

436 >>> from ase.build import bulk 

437 >>> from ase.calculators.emt import EMT 

438 >>> from ase.eos import calculate_eos 

439 

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 """ 

448 

449 # Save original positions and cell: 

450 p0 = atoms.get_positions() 

451 c0 = atoms.get_cell() 

452 

453 if isinstance(trajectory, str): 

454 from ase.io import Trajectory 

455 

456 trajectory = Trajectory(trajectory, 'w', atoms) 

457 

458 if trajectory is not None: 

459 trajectory.set_description( 

460 {'type': 'eos', 'npoints': npoints, 'eps': eps} 

461 ) 

462 

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() 

480 

481 

482class CLICommand: 

483 """Calculate EOS from one or more trajectory files. 

484 

485 See :ref:`eos_example` for more information. 

486 """ 

487 

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 ) 

505 

506 @staticmethod 

507 def run(args): 

508 from ase.io import read 

509 

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 

524 

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 )