Coverage for ase/calculators/lammpsrun.py: 87.68%

203 statements  

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

1"""ASE calculator for the LAMMPS classical MD code""" 

2# lammps.py (2011/03/29) 

3# 

4# Copyright (C) 2009 - 2011 Joerg Meyer, joerg.meyer@ch.tum.de 

5# 

6# This library is free software; you can redistribute it and/or 

7# modify it under the terms of the GNU Lesser General Public 

8# License as published by the Free Software Foundation; either 

9# version 2.1 of the License, or (at your option) any later version. 

10# 

11# This library is distributed in the hope that it will be useful, 

12# but WITHOUT ANY WARRANTY; without even the implied warranty of 

13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 

14# Lesser General Public License for more details. 

15# 

16# You should have received a copy of the GNU Lesser General Public 

17# License along with this file; if not, write to the Free Software 

18# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 

19# USA or see <https://www.gnu.org/licenses/>. 

20 

21import os 

22import shlex 

23import shutil 

24import subprocess 

25from contextlib import ExitStack 

26from re import IGNORECASE 

27from re import compile as re_compile 

28from tempfile import NamedTemporaryFile, mkdtemp 

29from tempfile import mktemp as uns_mktemp 

30from threading import Thread 

31from typing import Any 

32 

33import numpy as np 

34 

35from ase.calculators.calculator import Calculator, all_changes 

36from ase.calculators.lammps import ( 

37 CALCULATION_END_MARK, 

38 Prism, 

39 convert, 

40 write_lammps_in, 

41) 

42from ase.data import atomic_masses, chemical_symbols 

43from ase.io.lammpsdata import write_lammps_data 

44from ase.io.lammpsrun import read_lammps_dump 

45 

46__all__ = ['LAMMPS'] 

47 

48 

49class LAMMPS(Calculator): 

50 """LAMMPS (https://lammps.sandia.gov/) calculator 

51 

52 The environment variable :envvar:`ASE_LAMMPSRUN_COMMAND` must be defined to 

53 tell ASE how to call a LAMMPS binary. This should contain the path to the 

54 lammps binary, or more generally, a command line possibly also including an 

55 MPI-launcher command. 

56 

57 For example (in a Bourne-shell compatible environment): 

58 

59 .. code-block:: bash 

60 

61 export ASE_LAMMPSRUN_COMMAND=/path/to/lmp_binary 

62 

63 or possibly something similar to 

64 

65 .. code-block:: bash 

66 

67 export ASE_LAMMPSRUN_COMMAND="/path/to/mpirun --np 4 lmp_binary" 

68 

69 Parameters 

70 ---------- 

71 files : list[str] 

72 List of files needed by LAMMPS. Typically a list of potential files. 

73 parameters : dict[str, Any] 

74 Dictionary of settings to be passed into the input file for calculation. 

75 specorder : list[str] 

76 Within LAAMPS, atoms are identified by an integer value starting from 1. 

77 This variable allows the user to define the order of the indices 

78 assigned to the atoms in the calculation, with the default 

79 if not given being alphabetical 

80 keep_tmp_files : bool, default: False 

81 Retain any temporary files created. Mostly useful for debugging. 

82 tmp_dir : str, default: None 

83 path/dirname (default None -> create automatically). 

84 Explicitly control where the calculator object should create 

85 its files. Using this option implies 'keep_tmp_files=True'. 

86 no_data_file : bool, default: False 

87 Controls whether an explicit data file will be used for feeding 

88 atom coordinates into lammps. Enable it to lessen the pressure on 

89 the (tmp) file system. THIS OPTION MIGHT BE UNRELIABLE FOR CERTAIN 

90 CORNER CASES (however, if it fails, you will notice...). 

91 keep_alive : bool, default: True 

92 When using LAMMPS as a spawned subprocess, keep the subprocess 

93 alive (but idling when unused) along with the calculator object. 

94 always_triclinic : bool, default: False 

95 Force LAMMPS to treat the cell as tilted, even if the cell is not 

96 tilted, by printing ``xy``, ``xz``, ``yz`` in the data file. 

97 reduce_cell : bool, default: False 

98 If True, reduce cell to have shorter lattice vectors. 

99 write_velocities : bool, default: False 

100 If True, forward ASE velocities to LAMMPS. 

101 verbose: bool, default: False 

102 If True, print additional debugging output to STDOUT. 

103 

104 Examples 

105 -------- 

106 Provided that the respective potential file is in the working directory, 

107 one can simply run (note that LAMMPS needs to be compiled to work with EAM 

108 potentials) 

109 

110 :: 

111 

112 from ase import Atom, Atoms 

113 from ase.build import bulk 

114 from ase.calculators.lammpsrun import LAMMPS 

115 

116 parameters = {'pair_style': 'eam/alloy', 

117 'pair_coeff': ['* * NiAlH_jea.eam.alloy H Ni']} 

118 

119 files = ['NiAlH_jea.eam.alloy'] 

120 

121 Ni = bulk('Ni', cubic=True) 

122 H = Atom('H', position=Ni.cell.diagonal()/2) 

123 NiH = Ni + H 

124 

125 lammps = LAMMPS(files=files, **parameters) 

126 

127 NiH.calc = lammps 

128 print("Energy ", NiH.get_potential_energy()) 

129 """ 

130 

131 name = 'lammpsrun' 

132 implemented_properties = [ 

133 'energy', 

134 'free_energy', 

135 'forces', 

136 'stress', 

137 'energies', 

138 ] 

139 

140 # parameters to choose options in LAMMPSRUN 

141 ase_parameters: dict[str, Any] = dict( 

142 specorder=None, 

143 atorder=True, 

144 always_triclinic=False, 

145 reduce_cell=False, 

146 keep_alive=True, 

147 keep_tmp_files=False, 

148 no_data_file=False, 

149 tmp_dir=None, 

150 files=[], # usually contains potential parameters 

151 verbose=False, 

152 write_velocities=False, 

153 binary_dump=True, # bool - use binary dump files (full 

154 # precision but long long ids are casted to 

155 # double) 

156 lammps_options='-echo log -screen none -log /dev/stdout', 

157 trajectory_out=None, # file object, if is not None the 

158 # trajectory will be saved in it 

159 ) 

160 

161 # parameters forwarded to LAMMPS 

162 lammps_parameters = dict( 

163 boundary=None, # bounadry conditions styles 

164 units='metal', # str - Which units used; some potentials 

165 # require certain units 

166 atom_style='atomic', 

167 special_bonds=None, 

168 # potential informations 

169 pair_style='lj/cut 2.5', 

170 pair_coeff=['* * 1 1'], 

171 masses=None, 

172 pair_modify=None, 

173 # variables controlling the output 

174 thermo_args=[ 

175 'step', 

176 'temp', 

177 'press', 

178 'cpu', 

179 'pxx', 

180 'pyy', 

181 'pzz', 

182 'pxy', 

183 'pxz', 

184 'pyz', 

185 'ke', 

186 'pe', 

187 'etotal', 

188 'vol', 

189 'lx', 

190 'ly', 

191 'lz', 

192 'atoms', 

193 ], 

194 dump_properties=[ 

195 'id', 

196 'type', 

197 'x', 

198 'y', 

199 'z', 

200 'vx', 

201 'vy', 

202 'vz', 

203 'fx', 

204 'fy', 

205 'fz', 

206 ], 

207 dump_period=1, # period of system snapshot saving (in MD steps) 

208 ) 

209 

210 default_parameters = dict(ase_parameters, **lammps_parameters) 

211 

212 def __init__(self, label='lammps', **kwargs): 

213 super().__init__(label=label, **kwargs) 

214 

215 self.prism = None 

216 self.calls = 0 

217 self.forces = None 

218 # thermo_content contains data "written by" thermo_style. 

219 # It is a list of dictionaries, each dict (one for each line 

220 # printed by thermo_style) contains a mapping between each 

221 # custom_thermo_args-argument and the corresponding 

222 # value as printed by lammps. thermo_content will be 

223 # re-populated by the read_log method. 

224 self.thermo_content = [] 

225 

226 if self.parameters['tmp_dir'] is not None: 

227 # If tmp_dir is pointing somewhere, don't remove stuff! 

228 self.parameters['keep_tmp_files'] = True 

229 self._lmp_handle = None # To handle the lmp process 

230 

231 if self.parameters['tmp_dir'] is None: 

232 self.parameters['tmp_dir'] = mkdtemp(prefix='LAMMPS-') 

233 else: 

234 self.parameters['tmp_dir'] = os.path.realpath( 

235 self.parameters['tmp_dir'] 

236 ) 

237 if not os.path.isdir(self.parameters['tmp_dir']): 

238 os.mkdir(self.parameters['tmp_dir'], 0o755) 

239 

240 for f in self.parameters['files']: 

241 shutil.copy( 

242 f, os.path.join(self.parameters['tmp_dir'], os.path.basename(f)) 

243 ) 

244 

245 def get_lammps_command(self): 

246 cmd = self.parameters.get('command') 

247 

248 if cmd is None: 

249 from ase.config import cfg 

250 

251 envvar = f'ASE_{self.name.upper()}_COMMAND' 

252 cmd = cfg.get(envvar) 

253 

254 if cmd is None: 

255 # TODO deprecate and remove guesswork 

256 cmd = 'lammps' 

257 

258 opts = self.parameters.get('lammps_options') 

259 

260 if opts is not None: 

261 cmd = f'{cmd} {opts}' 

262 

263 return cmd 

264 

265 def clean(self, force=False): 

266 

267 self._lmp_end() 

268 

269 if not self.parameters['keep_tmp_files'] or force: 

270 shutil.rmtree(self.parameters['tmp_dir']) 

271 

272 def check_state(self, atoms, tol=1.0e-10): 

273 # Transforming the unit cell to conform to LAMMPS' convention for 

274 # orientation (c.f. https://lammps.sandia.gov/doc/Howto_triclinic.html) 

275 # results in some precision loss, so we use bit larger tolerance than 

276 # machine precision here. Note that there can also be precision loss 

277 # related to how many significant digits are specified for things in 

278 # the LAMMPS input file. 

279 return Calculator.check_state(self, atoms, tol) 

280 

281 def calculate(self, atoms=None, properties=None, system_changes=None): 

282 if properties is None: 

283 properties = self.implemented_properties 

284 if system_changes is None: 

285 system_changes = all_changes 

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

287 self.run() 

288 

289 def _lmp_alive(self): 

290 # Return True if this calculator is currently handling a running 

291 # lammps process 

292 return self._lmp_handle and not isinstance(self._lmp_handle.poll(), int) 

293 

294 def _lmp_end(self): 

295 # Close lammps input and wait for lammps to end. Return process 

296 # return value 

297 if self._lmp_alive(): 

298 # !TODO: handle lammps error codes 

299 try: 

300 self._lmp_handle.communicate(timeout=5) 

301 except subprocess.TimeoutExpired: 

302 self._lmp_handle.kill() 

303 self._lmp_handle.communicate() 

304 err = self._lmp_handle.poll() 

305 assert err is not None 

306 return err 

307 

308 def set_missing_parameters(self): 

309 """Verify that all necessary variables are set.""" 

310 symbols = self.atoms.get_chemical_symbols() 

311 # If unspecified default to atom types in alphabetic order 

312 if not self.parameters.get('specorder'): 

313 self.parameters['specorder'] = sorted(set(symbols)) 

314 

315 # !TODO: handle cases were setting masses actual lead to errors 

316 if not self.parameters.get('masses'): 

317 self.parameters['masses'] = [] 

318 for type_id, specie in enumerate(self.parameters['specorder']): 

319 mass = atomic_masses[chemical_symbols.index(specie)] 

320 self.parameters['masses'] += [f'{type_id + 1:d} {mass:f}'] 

321 

322 # set boundary condtions 

323 if not self.parameters.get('boundary'): 

324 b_str = ' '.join(['fp'[int(x)] for x in self.atoms.pbc]) 

325 self.parameters['boundary'] = b_str 

326 

327 def run(self, set_atoms=False): 

328 # !TODO: split this function 

329 """Method which explicitly runs LAMMPS.""" 

330 

331 with ExitStack() as exitstack: 

332 self._run(set_atoms, exitstack) 

333 

334 def _run(self, set_atoms, exitstack): 

335 cell = self.atoms.get_cell() 

336 if np.all(cell == 0.0): # without cell 

337 # large enough cell if it does not exist - 

338 # LAMMPS shrink-wraps automatically via input command 

339 # "periodic s s s" 

340 # below 

341 cell = 2 * np.max(np.abs(self.atoms.get_positions())) * np.eye(3) 

342 self.prism = Prism( 

343 cell, 

344 pbc=self.atoms.get_pbc(), 

345 reduce_cell=self.parameters['reduce_cell'], 

346 ) 

347 

348 self.set_missing_parameters() 

349 self.calls += 1 

350 

351 # change into subdirectory for LAMMPS calculations 

352 tempdir = self.parameters['tmp_dir'] 

353 

354 # setup file names for LAMMPS calculation 

355 label = f'{self.label}{self.calls:>06}' 

356 lammps_in = uns_mktemp(prefix='in_' + label, dir=tempdir) 

357 lammps_log = uns_mktemp(prefix='log_' + label, dir=tempdir) 

358 lammps_trj_fd = exitstack.enter_context( 

359 NamedTemporaryFile( 

360 prefix='trj_' + label, 

361 suffix=('.bin' if self.parameters['binary_dump'] else ''), 

362 dir=tempdir, 

363 delete=(not self.parameters['keep_tmp_files']), 

364 ) 

365 ) 

366 lammps_trj = lammps_trj_fd.name 

367 if self.parameters['no_data_file']: 

368 lammps_data = None 

369 else: 

370 lammps_data_fd = exitstack.enter_context( 

371 NamedTemporaryFile( 

372 prefix='data_' + label, 

373 dir=tempdir, 

374 delete=(not self.parameters['keep_tmp_files']), 

375 mode='w', 

376 encoding='ascii', 

377 ) 

378 ) 

379 write_lammps_data( 

380 lammps_data_fd, 

381 self.atoms, 

382 specorder=self.parameters['specorder'], 

383 force_skew=self.parameters['always_triclinic'], 

384 reduce_cell=self.parameters['reduce_cell'], 

385 velocities=self.parameters['write_velocities'], 

386 prismobj=self.prism, 

387 units=self.parameters['units'], 

388 atom_style=self.parameters['atom_style'], 

389 ) 

390 lammps_data = lammps_data_fd.name 

391 lammps_data_fd.flush() 

392 

393 # see to it that LAMMPS is started 

394 if not self._lmp_alive(): 

395 command = self.get_lammps_command() 

396 # Attempt to (re)start lammps 

397 self._lmp_handle = subprocess.Popen( 

398 shlex.split(command, posix=(os.name == 'posix')), 

399 stdin=subprocess.PIPE, 

400 stdout=subprocess.PIPE, 

401 text=True, 

402 ) 

403 lmp_handle = self._lmp_handle 

404 

405 # Create thread reading lammps stdout (for reference, if requested, 

406 # also create lammps_log, although it is never used) 

407 if self.parameters['keep_tmp_files']: 

408 lammps_log_fd = exitstack.enter_context(open(lammps_log, 'w')) 

409 fd = SpecialTee(lmp_handle.stdout, lammps_log_fd) 

410 else: 

411 fd = lmp_handle.stdout 

412 thr_read_log = Thread(target=self.read_lammps_log, args=(fd,)) 

413 thr_read_log.start() 

414 

415 # write LAMMPS input (for reference, also create the file lammps_in, 

416 # although it is never used) 

417 if self.parameters['keep_tmp_files']: 

418 lammps_in_fd = exitstack.enter_context(open(lammps_in, 'w')) 

419 fd = SpecialTee(lmp_handle.stdin, lammps_in_fd) 

420 else: 

421 fd = lmp_handle.stdin 

422 write_lammps_in( 

423 lammps_in=fd, 

424 parameters=self.parameters, 

425 atoms=self.atoms, 

426 prismobj=self.prism, 

427 lammps_trj=lammps_trj, 

428 lammps_data=lammps_data, 

429 ) 

430 

431 # Wait for log output to be read (i.e., for LAMMPS to finish) 

432 # and close the log file if there is one 

433 thr_read_log.join() 

434 

435 if not self.parameters['keep_alive']: 

436 self._lmp_end() 

437 

438 exitcode = lmp_handle.poll() 

439 if exitcode and exitcode != 0: 

440 raise RuntimeError( 

441 'LAMMPS exited in {} with exit code: {}.'.format( 

442 tempdir, exitcode 

443 ) 

444 ) 

445 

446 # A few sanity checks 

447 if len(self.thermo_content) == 0: 

448 raise RuntimeError('Failed to retrieve any thermo_style-output') 

449 if int(self.thermo_content[-1]['atoms']) != len(self.atoms): 

450 # This obviously shouldn't happen, but if prism.fold_...() fails, 

451 # it could 

452 raise RuntimeError('Atoms have gone missing') 

453 

454 trj_atoms = read_lammps_dump( 

455 infileobj=lammps_trj, 

456 order=self.parameters['atorder'], 

457 index=-1, 

458 prismobj=self.prism, 

459 specorder=self.parameters['specorder'], 

460 ) 

461 

462 if set_atoms: 

463 self.atoms = trj_atoms.copy() 

464 

465 self.forces = trj_atoms.get_forces() 

466 # !TODO: trj_atoms is only the last snapshot of the system; Is it 

467 # desirable to save also the inbetween steps? 

468 if self.parameters['trajectory_out'] is not None: 

469 # !TODO: is it advisable to create here temporary atoms-objects 

470 self.trajectory_out.write(trj_atoms) 

471 

472 tc = self.thermo_content[-1] 

473 self.results['energy'] = convert( 

474 tc['pe'], 'energy', self.parameters['units'], 'ASE' 

475 ) 

476 self.results['free_energy'] = self.results['energy'] 

477 self.results['forces'] = convert( 

478 self.forces.copy(), 'force', self.parameters['units'], 'ASE' 

479 ) 

480 stress = np.array( 

481 [-tc[i] for i in ('pxx', 'pyy', 'pzz', 'pyz', 'pxz', 'pxy')] 

482 ) 

483 

484 # We need to apply the Lammps rotation stuff to the stress: 

485 xx, yy, zz, yz, xz, xy = stress 

486 stress_tensor = np.array([[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]]) 

487 stress_atoms = self.prism.tensor2_to_ase(stress_tensor) 

488 stress_atoms = stress_atoms[[0, 1, 2, 1, 0, 0], [0, 1, 2, 2, 2, 1]] 

489 stress = stress_atoms 

490 

491 self.results['stress'] = convert( 

492 stress, 'pressure', self.parameters['units'], 'ASE' 

493 ) 

494 

495 def __enter__(self): 

496 return self 

497 

498 def __exit__(self, *args): 

499 self._lmp_end() 

500 

501 def read_lammps_log(self, fileobj): 

502 # !TODO: somehow communicate 'thermo_content' explicitly 

503 """Method which reads a LAMMPS output log file.""" 

504 

505 # read_log depends on that the first (three) thermo_style custom args 

506 # can be capitalized and matched against the log output. I.e. 

507 # don't use e.g. 'ke' or 'cpu' which are labeled KinEng and CPU. 

508 mark_re = r'^\s*' + r'\s+'.join( 

509 [x.capitalize() for x in self.parameters['thermo_args'][0:3]] 

510 ) 

511 _custom_thermo_mark = re_compile(mark_re) 

512 

513 # !TODO: regex-magic necessary? 

514 # Match something which can be converted to a float 

515 f_re = r'([+-]?(?:(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|nan|inf))' 

516 n_args = len(self.parameters['thermo_args']) 

517 # Create a re matching exactly N white space separated floatish things 

518 _custom_thermo_re = re_compile( 

519 r'^\s*' + r'\s+'.join([f_re] * n_args) + r'\s*$', flags=IGNORECASE 

520 ) 

521 

522 thermo_content = [] 

523 line = fileobj.readline() 

524 while line and line.strip() != CALCULATION_END_MARK: 

525 # check error 

526 if 'ERROR:' in line: 

527 raise RuntimeError(f'LAMMPS exits with error message: {line}') 

528 

529 # get thermo output 

530 if _custom_thermo_mark.match(line): 

531 while True: 

532 line = fileobj.readline() 

533 if 'WARNING:' in line: 

534 continue 

535 

536 bool_match = _custom_thermo_re.match(line) 

537 if not bool_match: 

538 break 

539 

540 # create a dictionary between each of the 

541 # thermo_style args and it's corresponding value 

542 thermo_content.append( 

543 dict( 

544 zip( 

545 self.parameters['thermo_args'], 

546 map(float, bool_match.groups()), 

547 ) 

548 ) 

549 ) 

550 else: 

551 line = fileobj.readline() 

552 

553 self.thermo_content = thermo_content 

554 

555 

556class SpecialTee: 

557 """A special purpose, with limited applicability, tee-like thing. 

558 

559 A subset of stuff read from, or written to, orig_fd, 

560 is also written to out_fd. 

561 It is used by the lammps calculator for creating file-logs of stuff 

562 read from, or written to, stdin and stdout, respectively. 

563 """ 

564 

565 def __init__(self, orig_fd, out_fd): 

566 self._orig_fd = orig_fd 

567 self._out_fd = out_fd 

568 self.name = orig_fd.name 

569 

570 def write(self, data): 

571 self._orig_fd.write(data) 

572 self._out_fd.write(data) 

573 self.flush() 

574 

575 def read(self, *args, **kwargs): 

576 data = self._orig_fd.read(*args, **kwargs) 

577 self._out_fd.write(data) 

578 return data 

579 

580 def readline(self, *args, **kwargs): 

581 data = self._orig_fd.readline(*args, **kwargs) 

582 self._out_fd.write(data) 

583 return data 

584 

585 def readlines(self, *args, **kwargs): 

586 data = self._orig_fd.readlines(*args, **kwargs) 

587 self._out_fd.write(''.join(data)) 

588 return data 

589 

590 def flush(self): 

591 self._orig_fd.flush() 

592 self._out_fd.flush()