Coverage for ase/calculators/lammpslib.py: 79.85%

263 statements  

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

1"""ASE LAMMPS Calculator Library Version""" 

2 

3import ctypes 

4 

5import numpy as np 

6 

7from ase import Atoms 

8from ase.calculators.calculator import Calculator 

9from ase.calculators.lammps import Prism, convert 

10from ase.data import atomic_masses as ase_atomic_masses 

11from ase.data import atomic_numbers as ase_atomic_numbers 

12from ase.data import chemical_symbols as ase_chemical_symbols 

13 

14# TODO 

15# 1. should we make a new lammps object each time ? 

16# 4. need a routine to get the model back from lammps 

17# 5. if we send a command to lmps directly then the calculator does 

18# not know about it and the energy could be wrong. 

19# 6. do we need a subroutine generator that converts a lammps string 

20# into a python function that can be called 

21# 8. make matscipy as fallback 

22# 9. keep_alive not needed with no system changes 

23 

24 

25class LAMMPSlib(Calculator): 

26 r""" 

27 **Introduction** 

28 

29 LAMMPSlib is an interface and calculator for LAMMPS_. LAMMPSlib uses 

30 the python interface that comes with LAMMPS to solve an atoms model 

31 for energy, atom forces and cell stress. This calculator creates a 

32 '.lmp' object which is a running lammps program, so further commands 

33 can be sent to this object executed until it is explicitly closed. Any 

34 additional variables calculated by lammps can also be extracted. This 

35 is still experimental code. 

36 

37 **Arguments** 

38 

39 ======================= =================================================== 

40 Keyword Description 

41 ======================= =================================================== 

42 ``lmpcmds`` list of strings of LAMMPS commands. You need to 

43 supply 

44 enough to define the potential to be used e.g. 

45 

46 ["pair_style eam/alloy", 

47 "pair_coeff * * potentials/NiAlH_jea.eam.alloy 

48 Ni Al"] 

49 

50 ``atom_types`` dictionary of ``atomic_symbol :lammps_atom_type`` 

51 pairs, e.g. ``{'Cu':1}`` to bind copper to lammps 

52 atom type 1. If <None>, autocreated by assigning 

53 lammps atom types in order that they appear in the 

54 first used atoms object. 

55 

56 ``atom_type_masses`` dictionary of ``atomic_symbol :mass`` pairs, e.g. 

57 ``{'Cu':63.546}`` to optionally assign masses that 

58 override default ase.data.atomic_masses. Note that 

59 since unit conversion is done automatically in this 

60 module, these quantities must be given in the 

61 standard ase mass units (g/mol) 

62 

63 ``log_file`` string 

64 path to the desired LAMMPS log file 

65 

66 ``lammps_header`` string to use for lammps setup. Default is to use 

67 metal units and simple atom simulation. 

68 

69 lammps_header=['units metal', 

70 'atom_style atomic', 

71 'atom_modify map array sort 0 0']) 

72 

73 ``amendments`` extra list of strings of LAMMPS commands to be run 

74 post initialization. 

75 (Use: Initialization amendments) 

76 e.g. 

77 

78 ["mass 1 58.6934"] 

79 

80 ``post_changebox_cmds`` extra list of strings of LAMMPS commands to be run 

81 after any LAMMPS 'change_box' command is 

82 performed by 

83 the calculator. This is relevant because some 

84 potentials either themselves depend on the geometry 

85 and boundary conditions of the simulation box, 

86 or are 

87 frequently coupled with other LAMMPS commands that 

88 do, e.g. the 'buck/coul/long' pair style is often 

89 used with the kspace_* commands, which are 

90 sensitive 

91 to the periodicity of the simulation box. 

92 

93 ``extra_cmd_args`` list of extra arguments for 

94 `lammps.lammps(cmd_args=...)`, e.g. for kokkos 

95 mliap on a gpu 

96 ``` 

97 ("-k on g 1 -sf kk " 

98 "-pk kokkos neigh half newton on").split() 

99 ``` 

100 

101 ``intializer`` callback function that does arbitrary LAMMPS python 

102 API initializtion tasks (e.g. calling 

103 `lammps.mliap.activate_mliapy`) and accepts a 

104 single positional argument, `self.lmp`. 

105 

106 ``keep_alive`` Boolean 

107 whether to keep the lammps routine alive for more 

108 commands. Default is True. 

109 

110 ======================= =================================================== 

111 

112 

113 **Requirements** 

114 

115 To run this calculator you must have LAMMPS installed and compiled to 

116 enable the python interface. See the LAMMPS manual. 

117 

118 If the following code runs then lammps is installed correctly. 

119 

120 >>> from lammps import lammps 

121 >>> lmp = lammps() 

122 

123 The version of LAMMPS is also important. LAMMPSlib is suitable for 

124 versions after approximately 2011. Prior to this the python interface 

125 is slightly different from that used by LAMMPSlib. It is not difficult 

126 to change to the earlier format. 

127 

128 **LAMMPS and LAMMPSlib** 

129 

130 The LAMMPS calculator is another calculator that uses LAMMPS (the 

131 program) to calculate the energy by generating input files and running 

132 a separate LAMMPS job to perform the analysis. The output data is then 

133 read back into python. LAMMPSlib makes direct use of the LAMMPS (the 

134 program) python interface. As well as directly running any LAMMPS 

135 command line it allows the values of any of LAMMPS variables to be 

136 extracted and returned to python. 

137 

138 **Example** 

139 

140 Provided that the respective potential file is in the working directory, one 

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

142 potentials) 

143 

144 :: 

145 

146 from ase import Atom, Atoms 

147 from ase.build import bulk 

148 from ase.calculators.lammpslib import LAMMPSlib 

149 

150 cmds = ["pair_style eam/alloy", 

151 "pair_coeff * * NiAlH_jea.eam.alloy Ni H"] 

152 

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

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

155 NiH = Ni + H 

156 

157 lammps = LAMMPSlib(lmpcmds=cmds, log_file='test.log') 

158 

159 NiH.calc = lammps 

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

161 

162 

163 **Implementation** 

164 

165 LAMMPS provides a set of python functions to allow execution of the 

166 underlying C++ LAMMPS code. The functions used by the LAMMPSlib 

167 interface are:: 

168 

169 from lammps import lammps 

170 

171 lmp = lammps(cmd_args) # initiate LAMMPS object with command line args 

172 

173 lmp.scatter_atoms('x',1,3,positions) # atom coords to LAMMPS C array 

174 lmp.command(cmd) # executes a one line cmd string 

175 lmp.extract_variable(...) # extracts a per atom variable 

176 lmp.extract_global(...) # extracts a global variable 

177 lmp.close() # close the lammps object 

178 

179 For a single Ni atom model the following lammps file commands would be run 

180 by invoking the get_potential_energy() method:: 

181 

182 units metal 

183 atom_style atomic 

184 atom_modify map array sort 0 0 

185 

186 region cell prism 0 xhi 0 yhi 0 zhi xy xz yz units box 

187 create_box 1 cell 

188 create_atoms 1 single 0 0 0 units box 

189 mass * 1.0 

190 

191 ## user lmpcmds get executed here 

192 pair_style eam/alloy 

193 pair_coeff * * NiAlH_jea.eam.alloy Ni 

194 ## end of user lmmpcmds 

195 

196 run 0 

197 

198 where xhi, yhi and zhi are the lattice vector lengths and xy, 

199 xz and yz are the tilt of the lattice vectors, all to be edited. 

200 

201 

202 **Notes** 

203 

204 .. _LAMMPS: https://lammps.org/ 

205 

206 * Units: The default lammps_header sets the units to Angstrom and eV 

207 and for compatibility with ASE Stress is in GPa. 

208 

209 * The global energy is currently extracted from LAMMPS using 

210 extract_variable since lammps.lammps currently extract_global only 

211 accepts the following ['dt', 'boxxlo', 'boxxhi', 'boxylo', 'boxyhi', 

212 'boxzlo', 'boxzhi', 'natoms', 'nlocal']. 

213 

214 * If an error occurs while lammps is in control it will crash 

215 Python. Check the output of the log file to find the lammps error. 

216 

217 * If the are commands directly sent to the LAMMPS object this may 

218 change the energy value of the model. However the calculator will not 

219 know of it and still return the original energy value. 

220 

221 """ 

222 

223 implemented_properties = [ 

224 'energy', 

225 'free_energy', 

226 'forces', 

227 'stress', 

228 'energies', 

229 ] 

230 

231 started = False 

232 initialized = False 

233 

234 default_parameters = dict( 

235 atom_types=None, 

236 atom_type_masses=None, 

237 log_file=None, 

238 lammps_name='', 

239 keep_alive=True, 

240 lammps_header=[ 

241 'units metal', 

242 'atom_style atomic', 

243 'atom_modify map array sort 0 0', 

244 ], 

245 amendments=None, 

246 post_changebox_cmds=None, 

247 extra_cmd_args=(), 

248 initializer=None, 

249 boundary=True, 

250 create_box=True, 

251 create_atoms=True, 

252 read_molecular_info=False, 

253 comm=None, 

254 ) 

255 

256 def __init__(self, *args, **kwargs): 

257 Calculator.__init__(self, *args, **kwargs) 

258 self.lmp = None 

259 

260 def __enter__(self): 

261 return self 

262 

263 def __exit__(self, *args): 

264 self.clean() 

265 

266 def clean(self): 

267 if self.started: 

268 self.lmp.close() 

269 self.started = False 

270 self.initialized = False 

271 self.lmp = None 

272 

273 def set_cell(self, atoms: Atoms, change: bool = False): 

274 self.prism = Prism(atoms.cell, atoms.pbc) 

275 _ = self.prism.get_lammps_prism() 

276 xhi, yhi, zhi, xy, xz, yz = convert(_, 'distance', 'ASE', self.units) 

277 box_hi = [xhi, yhi, zhi] 

278 

279 if change: 

280 cell_cmd = ( 

281 'change_box all ' 

282 'x final 0 {} y final 0 {} z final 0 {} ' 

283 'xy final {} xz final {} yz final {} units box' 

284 ''.format(xhi, yhi, zhi, xy, xz, yz) 

285 ) 

286 if self.parameters.post_changebox_cmds is not None: 

287 for cmd in self.parameters.post_changebox_cmds: 

288 self.lmp.command(cmd) 

289 else: 

290 # just in case we'll want to run with a funny shape box, 

291 # and here command will only happen once, and before 

292 # any calculation 

293 if self.parameters.create_box: 

294 self.lmp.command('box tilt large') 

295 

296 # Check if there are any indefinite boundaries. If so, 

297 # shrink-wrapping will end up being used, but we want to 

298 # define the LAMMPS region and box fairly tight around the 

299 # atoms to avoid losing any 

300 lammps_boundary_conditions = self.lammpsbc(atoms).split() 

301 if 's' in lammps_boundary_conditions: 

302 pos = self.prism.vector_to_lammps(atoms.positions) 

303 posmin = np.amin(pos, axis=0) 

304 posmax = np.amax(pos, axis=0) 

305 

306 for i in range(3): 

307 if lammps_boundary_conditions[i] == 's': 

308 box_hi[i] = 1.05 * abs(posmax[i] - posmin[i]) 

309 

310 cell_cmd = ( 

311 'region cell prism ' 

312 '0 {} 0 {} 0 {} ' 

313 '{} {} {} units box' 

314 ''.format(*box_hi, xy, xz, yz) 

315 ) 

316 

317 self.lmp.command(cell_cmd) 

318 

319 def set_lammps_pos(self, atoms: Atoms): 

320 # Create local copy of positions that are wrapped along any periodic 

321 # directions 

322 pos = convert(atoms.positions, 'distance', 'ASE', self.units) 

323 

324 # wrap only after scaling and rotating to reduce chances of 

325 # lammps neighbor list bugs. 

326 pos = self.prism.vector_to_lammps(pos, wrap=True) 

327 

328 # Convert ase position matrix to lammps-style position array 

329 # contiguous in memory 

330 lmp_positions = list(pos.ravel()) 

331 

332 # Convert that lammps-style array into a C object 

333 c_double_array = ctypes.c_double * len(lmp_positions) 

334 lmp_c_positions = c_double_array(*lmp_positions) 

335 # self.lmp.put_coosrds(lmp_c_positions) 

336 self.lmp.scatter_atoms('x', 1, 3, lmp_c_positions) 

337 

338 def calculate(self, atoms, properties, system_changes): 

339 self.propagate(atoms, properties, system_changes, 0) 

340 

341 def propagate( 

342 self, 

343 atoms, 

344 properties, 

345 system_changes, 

346 n_steps, 

347 dt=None, 

348 dt_not_real_time=False, 

349 velocity_field=None, 

350 ): 

351 """ "atoms: Atoms object 

352 Contains positions, unit-cell, ... 

353 properties: list of str 

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

355 of 'energy', 'forces', 'stress', 'dipole', 'charges', 'magmom' 

356 and 'magmoms'. 

357 system_changes: list of str 

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

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

360 'pbc', 'initial_charges' and 'initial_magmoms'. 

361 """ 

362 if len(system_changes) == 0: 

363 return 

364 

365 if not self.started: 

366 self.start_lammps() 

367 if not self.initialized: 

368 self.initialise_lammps(atoms) 

369 else: # still need to reset cell 

370 # NOTE: The whole point of ``post_changebox_cmds`` is that they're 

371 # executed after any call to LAMMPS' change_box command. Here, we 

372 # rely on the fact that self.set_cell(), where we have currently 

373 # placed the execution of ``post_changebox_cmds``, gets called 

374 # after this initial change_box call. 

375 

376 # Apply only requested boundary condition changes. Note this needs 

377 # to happen before the call to set_cell since 'change_box' will 

378 # apply any shrink-wrapping *after* it's updated the cell 

379 # dimensions 

380 if 'pbc' in system_changes: 

381 change_box_str = 'change_box all boundary {}' 

382 change_box_cmd = change_box_str.format(self.lammpsbc(atoms)) 

383 self.lmp.command(change_box_cmd) 

384 

385 # Reset positions so that if they are crazy from last 

386 # propagation, change_box (in set_cell()) won't hang. 

387 # Could do this only after testing for crazy positions? 

388 # Could also use scatter_atoms() to set values (requires 

389 # MPI comm), or extra_atoms() to get pointers to local 

390 # data structures to zero, but then we would have to be 

391 # careful with parallelism. 

392 self.lmp.command('set atom * x 0.0 y 0.0 z 0.0') 

393 self.set_cell(atoms, change=True) 

394 

395 if self.parameters.atom_types is None: 

396 raise NameError('atom_types are mandatory.') 

397 

398 do_rebuild = not np.array_equal( 

399 atoms.numbers, self.previous_atoms_numbers 

400 ) or any(_ in system_changes for _ in ('numbers', 'initial_charges')) 

401 if not do_rebuild: 

402 do_redo_atom_types = not np.array_equal( 

403 atoms.numbers, self.previous_atoms_numbers 

404 ) 

405 else: 

406 do_redo_atom_types = False 

407 

408 self.lmp.command('echo none') # don't echo the atom positions 

409 if do_rebuild: 

410 self.rebuild(atoms) 

411 elif do_redo_atom_types: 

412 self.redo_atom_types(atoms) 

413 self.lmp.command('echo log') # switch back log 

414 

415 self.set_lammps_pos(atoms) 

416 

417 if self.parameters.amendments is not None: 

418 for cmd in self.parameters.amendments: 

419 self.lmp.command(cmd) 

420 

421 if n_steps > 0: 

422 if velocity_field is None: 

423 vel = convert( 

424 atoms.get_velocities(), 'velocity', 'ASE', self.units 

425 ) 

426 else: 

427 # FIXME: Do we need to worry about converting to lammps units 

428 # here? 

429 vel = atoms.arrays[velocity_field] 

430 

431 # Transform the velocities to new coordinate system 

432 vel = self.prism.vector_to_lammps(vel) 

433 

434 # Convert ase velocities matrix to lammps-style velocities array 

435 lmp_velocities = list(vel.ravel()) 

436 

437 # Convert that lammps-style array into a C object 

438 c_double_array = ctypes.c_double * len(lmp_velocities) 

439 lmp_c_velocities = c_double_array(*lmp_velocities) 

440 self.lmp.scatter_atoms('v', 1, 3, lmp_c_velocities) 

441 

442 # Run for 0 time to calculate 

443 if dt is not None: 

444 if dt_not_real_time: 

445 self.lmp.command('timestep %.30f' % dt) 

446 else: 

447 self.lmp.command( 

448 'timestep %.30f' % convert(dt, 'time', 'ASE', self.units) 

449 ) 

450 self.lmp.command('run %d' % n_steps) 

451 

452 if n_steps > 0: 

453 # TODO this must be slower than native copy, but why is it broken? 

454 pos = np.array( 

455 [x for x in self.lmp.gather_atoms('x', 1, 3)] 

456 ).reshape(-1, 3) 

457 pos = self.prism.vector_to_ase(pos) 

458 

459 # Convert from LAMMPS units to ASE units 

460 pos = convert(pos, 'distance', self.units, 'ASE') 

461 

462 atoms.set_positions(pos) 

463 

464 vel = np.array( 

465 [v for v in self.lmp.gather_atoms('v', 1, 3)] 

466 ).reshape(-1, 3) 

467 vel = self.prism.vector_to_lammps(vel) 

468 if velocity_field is None: 

469 atoms.set_velocities( 

470 convert(vel, 'velocity', self.units, 'ASE') 

471 ) 

472 

473 # Extract the forces and energy 

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

475 self.lmp.extract_variable('pe', None, 0), 

476 'energy', 

477 self.units, 

478 'ASE', 

479 ) 

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

481 

482 # check for MPI active as per https://matsci.org/t/lammps-ids-in-python/60509/5 

483 world_size = self.lmp.extract_setting('world_size') 

484 if world_size != 1: 

485 raise RuntimeError( 

486 'Unsupported MPI active as indicated by ' 

487 f'world_size == {world_size} != 1' 

488 ) 

489 # select just n_local which we assume is equal to len(atoms) 

490 ids = self.lmp.numpy.extract_atom('id')[0 : len(atoms)] 

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

492 self.lmp.numpy.extract_compute( 

493 'pe_peratom', self.LMP_STYLE_ATOM, self.LMP_TYPE_VECTOR 

494 ), 

495 'energy', 

496 self.units, 

497 'ASE', 

498 ) 

499 self.results['energies'][ids - 1] = self.results['energies'] 

500 

501 stress = np.empty(6) 

502 stress_vars = ['pxx', 'pyy', 'pzz', 'pyz', 'pxz', 'pxy'] 

503 

504 for i, var in enumerate(stress_vars): 

505 stress[i] = self.lmp.extract_variable(var, None, 0) 

506 

507 stress_mat = np.zeros((3, 3)) 

508 stress_mat[0, 0] = stress[0] 

509 stress_mat[1, 1] = stress[1] 

510 stress_mat[2, 2] = stress[2] 

511 stress_mat[1, 2] = stress[3] 

512 stress_mat[2, 1] = stress[3] 

513 stress_mat[0, 2] = stress[4] 

514 stress_mat[2, 0] = stress[4] 

515 stress_mat[0, 1] = stress[5] 

516 stress_mat[1, 0] = stress[5] 

517 

518 stress_mat = self.prism.tensor2_to_ase(stress_mat) 

519 

520 stress[0] = stress_mat[0, 0] 

521 stress[1] = stress_mat[1, 1] 

522 stress[2] = stress_mat[2, 2] 

523 stress[3] = stress_mat[1, 2] 

524 stress[4] = stress_mat[0, 2] 

525 stress[5] = stress_mat[0, 1] 

526 

527 self.results['stress'] = convert(-stress, 'pressure', self.units, 'ASE') 

528 

529 # definitely yields atom-id ordered force array 

530 f = convert( 

531 np.array(self.lmp.gather_atoms('f', 1, 3)).reshape(-1, 3), 

532 'force', 

533 self.units, 

534 'ASE', 

535 ) 

536 self.results['forces'] = self.prism.vector_to_ase(f) 

537 

538 # otherwise check_state will always trigger a new calculation 

539 self.atoms = atoms.copy() 

540 

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

542 self.clean() 

543 

544 def lammpsbc(self, atoms): 

545 """Determine LAMMPS boundary types based on ASE pbc settings. For 

546 non-periodic dimensions, if the cell length is finite then 

547 fixed BCs ('f') are used; if the cell length is approximately 

548 zero, shrink-wrapped BCs ('s') are used.""" 

549 

550 retval = '' 

551 pbc = atoms.get_pbc() 

552 if np.all(pbc): 

553 retval = 'p p p' 

554 else: 

555 cell = atoms.get_cell() 

556 for i in range(3): 

557 if pbc[i]: 

558 retval += 'p ' 

559 else: 

560 # See if we're using indefinite ASE boundaries along this 

561 # direction 

562 if np.linalg.norm(cell[i]) < np.finfo(cell[i][0]).tiny: 

563 retval += 's ' 

564 else: 

565 retval += 'f ' 

566 

567 return retval.strip() 

568 

569 def rebuild(self, atoms): 

570 try: 

571 n_diff = len(atoms.numbers) - len(self.previous_atoms_numbers) 

572 except Exception: # XXX Which kind of exception? 

573 n_diff = len(atoms.numbers) 

574 

575 if n_diff > 0: 

576 if any(('reax/c' in cmd) for cmd in self.parameters.lmpcmds): 

577 self.lmp.command('pair_style lj/cut 2.5') 

578 self.lmp.command('pair_coeff * * 1 1') 

579 

580 for cmd in self.parameters.lmpcmds: 

581 if ( 

582 ('pair_style' in cmd) 

583 or ('pair_coeff' in cmd) 

584 or ('qeq/reax' in cmd) 

585 ): 

586 self.lmp.command(cmd) 

587 

588 cmd = f'create_atoms 1 random {n_diff} 1 NULL' 

589 self.lmp.command(cmd) 

590 elif n_diff < 0: 

591 cmd = 'group delatoms id {}:{}'.format( 

592 len(atoms.numbers) + 1, len(self.previous_atoms_numbers) 

593 ) 

594 self.lmp.command(cmd) 

595 cmd = 'delete_atoms group delatoms' 

596 self.lmp.command(cmd) 

597 

598 self.redo_atom_types(atoms) 

599 

600 def redo_atom_types(self, atoms): 

601 current_types = { 

602 (i + 1, self.parameters.atom_types[sym]) 

603 for i, sym in enumerate(atoms.get_chemical_symbols()) 

604 } 

605 

606 try: 

607 previous_types = { 

608 (i + 1, self.parameters.atom_types[ase_chemical_symbols[Z]]) 

609 for i, Z in enumerate(self.previous_atoms_numbers) 

610 } 

611 except Exception: # XXX which kind of exception? 

612 previous_types = set() 

613 

614 for i, i_type in current_types - previous_types: 

615 cmd = f'set atom {i} type {i_type}' 

616 self.lmp.command(cmd) 

617 

618 # set charges only when LAMMPS `atom_style` permits charges 

619 # https://docs.lammps.org/Library_properties.html#extract-atom-flags 

620 if self.lmp.extract_setting('q_flag') == 1: 

621 charges = atoms.get_initial_charges() 

622 if np.any(charges != 0.0): 

623 for i, q in enumerate(charges): 

624 self.lmp.command(f'set atom {i + 1} charge {q}') 

625 

626 self.previous_atoms_numbers = atoms.numbers.copy() 

627 

628 def restart_lammps(self, atoms): 

629 if self.started: 

630 self.lmp.command('clear') 

631 # hope there's no other state to be reset 

632 self.started = False 

633 self.initialized = False 

634 self.previous_atoms_numbers = [] 

635 self.start_lammps() 

636 self.initialise_lammps(atoms) 

637 

638 def start_lammps(self): 

639 # Only import lammps when running a calculation 

640 # so it is not required to use other parts of the 

641 # module 

642 from lammps import LMP_STYLE_ATOM, LMP_TYPE_VECTOR, lammps 

643 

644 self.LMP_STYLE_ATOM = LMP_STYLE_ATOM 

645 self.LMP_TYPE_VECTOR = LMP_TYPE_VECTOR 

646 

647 # start lammps process 

648 if self.parameters.log_file is None: 

649 cmd_args = [ 

650 '-echo', 

651 'log', 

652 '-log', 

653 'none', 

654 '-screen', 

655 'none', 

656 '-nocite', 

657 ] 

658 else: 

659 cmd_args = [ 

660 '-echo', 

661 'log', 

662 '-log', 

663 self.parameters.log_file, 

664 '-screen', 

665 'none', 

666 '-nocite', 

667 ] 

668 

669 self.cmd_args = cmd_args + list(self.parameters.extra_cmd_args) 

670 

671 if self.lmp is None: 

672 self.lmp = lammps( 

673 self.parameters.lammps_name, 

674 self.cmd_args, 

675 comm=self.parameters.comm, 

676 ) 

677 

678 if self.parameters.initializer is not None: 

679 self.parameters.initializer(self.lmp) 

680 

681 # Run header commands to set up lammps (units, etc.) 

682 for cmd in self.parameters.lammps_header: 

683 self.lmp.command(cmd) 

684 

685 for cmd in self.parameters.lammps_header: 

686 if 'units' in cmd: 

687 self.units = cmd.split()[1] 

688 

689 if 'lammps_header_extra' in self.parameters: 

690 if self.parameters.lammps_header_extra is not None: 

691 for cmd in self.parameters.lammps_header_extra: 

692 self.lmp.command(cmd) 

693 

694 self.started = True 

695 

696 def initialise_lammps(self, atoms): 

697 # Initialising commands 

698 if self.parameters.boundary: 

699 # if the boundary command is in the supplied commands use that 

700 # otherwise use atoms pbc 

701 for cmd in self.parameters.lmpcmds: 

702 if 'boundary' in cmd: 

703 break 

704 else: 

705 self.lmp.command('boundary ' + self.lammpsbc(atoms)) 

706 

707 # Initialize cell 

708 self.set_cell(atoms, change=not self.parameters.create_box) 

709 

710 if self.parameters.atom_types is None: 

711 # if None is given, create from atoms object in order of appearance 

712 s = atoms.get_chemical_symbols() 

713 _, idx = np.unique(s, return_index=True) 

714 s_red = np.array(s)[np.sort(idx)].tolist() 

715 self.parameters.atom_types = {j: i + 1 for i, j in enumerate(s_red)} 

716 

717 # Initialize box 

718 if self.parameters.create_box: 

719 # count number of known types 

720 n_types = len(self.parameters.atom_types) 

721 create_box_command = f'create_box {n_types} cell' 

722 self.lmp.command(create_box_command) 

723 

724 # Initialize the atoms with their types 

725 # positions do not matter here 

726 if self.parameters.create_atoms: 

727 self.lmp.command('echo none') # don't echo the atom positions 

728 self.rebuild(atoms) 

729 self.lmp.command('echo log') # turn back on 

730 else: 

731 self.previous_atoms_numbers = atoms.numbers.copy() 

732 

733 # execute the user commands 

734 for cmd in self.parameters.lmpcmds + ['compute pe_peratom all pe/atom']: 

735 self.lmp.command(cmd) 

736 

737 # Set masses after user commands, e.g. to override 

738 # EAM-provided masses 

739 for sym in self.parameters.atom_types: 

740 if self.parameters.atom_type_masses is None: 

741 mass = ase_atomic_masses[ase_atomic_numbers[sym]] 

742 else: 

743 mass = self.parameters.atom_type_masses[sym] 

744 self.lmp.command( 

745 'mass %d %.30f' 

746 % ( 

747 self.parameters.atom_types[sym], 

748 convert(mass, 'mass', 'ASE', self.units), 

749 ) 

750 ) 

751 

752 # Define force & energy variables for extraction 

753 self.lmp.command('variable pxx equal pxx') 

754 self.lmp.command('variable pyy equal pyy') 

755 self.lmp.command('variable pzz equal pzz') 

756 self.lmp.command('variable pxy equal pxy') 

757 self.lmp.command('variable pxz equal pxz') 

758 self.lmp.command('variable pyz equal pyz') 

759 

760 # I am not sure why we need this next line but LAMMPS will 

761 # raise an error if it is not there. Perhaps it is needed to 

762 # ensure the cell stresses are calculated 

763 self.lmp.command('thermo_style custom pe pxx emol ecoul') 

764 

765 self.lmp.command('variable fx atom fx') 

766 self.lmp.command('variable fy atom fy') 

767 self.lmp.command('variable fz atom fz') 

768 

769 # do we need this if we extract from a global ? 

770 self.lmp.command('variable pe equal pe') 

771 

772 self.lmp.command('neigh_modify delay 0 every 1 check yes') 

773 

774 self.initialized = True