Coverage for ase/io/lammpsrun.py: 90.58%

276 statements  

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

1"""IO for LAMMPS dump files.""" 

2 

3import gzip 

4import struct 

5from collections.abc import Iterator 

6from os.path import splitext 

7from typing import IO, Any, TextIO 

8 

9import numpy as np 

10 

11from ase.atoms import Atoms 

12from ase.calculators.lammps import convert 

13from ase.calculators.singlepoint import SinglePointCalculator 

14from ase.data import atomic_masses, chemical_symbols 

15from ase.io.utils import ImageChunk, ImageIterator 

16from ase.parallel import paropen 

17from ase.utils import reader 

18 

19 

20def read_lammps_dump(infileobj, **kwargs): 

21 """Method which reads a LAMMPS dump file. 

22 

23 LAMMPS chooses output method depending on the given suffix: 

24 - .bin : binary file 

25 - .gz : output piped through gzip 

26 - .mpiio: using mpiio (should be like cleartext, 

27 with different ordering) 

28 - else : normal clear-text format 

29 

30 Parameters 

31 ---------- 

32 infileobj : str | IOBase 

33 File name in ``str``, opened file or file-like stream. 

34 

35 """ 

36 # !TODO: add support for lammps-regex naming schemes (output per 

37 # processor and timestep wildcards) 

38 

39 opened = False 

40 if isinstance(infileobj, str): 

41 opened = True 

42 suffix = splitext(infileobj)[-1] 

43 if suffix == '.bin': 

44 fileobj = paropen(infileobj, 'rb') 

45 elif suffix == '.gz': 

46 # !TODO: save for parallel execution? 

47 fileobj = gzip.open(infileobj, 'rb') 

48 else: 

49 fileobj = paropen(infileobj) 

50 else: 

51 suffix = splitext(infileobj.name)[-1] 

52 fileobj = infileobj 

53 

54 if suffix == '.bin': 

55 out = read_lammps_dump_binary(fileobj, **kwargs) 

56 if opened: 

57 fileobj.close() 

58 return out 

59 

60 out = read_lammps_dump_text(fileobj, **kwargs) 

61 

62 if opened: 

63 fileobj.close() 

64 

65 return out 

66 

67 

68def _lammps_data_to_ase_atoms( 

69 data, 

70 colnames, 

71 cell, 

72 celldisp, 

73 pbc=False, 

74 order=True, 

75 specorder=None, 

76 prismobj=None, 

77 units='metal', 

78): 

79 """Extract positions and other per-atom parameters and create Atoms. 

80 

81 Parameters 

82 ---------- 

83 data : np.ndarray 

84 Structured array for `ITEM: ATOMS`. 

85 colnames: list[str] 

86 Column names for `ITEM: ATOMS`. 

87 cell : np.ndarray 

88 Cell. 

89 celldisp : np.ndarray 

90 Origin shift. 

91 pbc : bool | list[bool] 

92 Periodic boundary conditions. 

93 order : bool 

94 Sort atoms by `id`. Might be faster to turn off. 

95 Disregarded in case `id` column is not given in file. 

96 specorder : list[str] 

97 List of species to map LAMMPS types to ASE species. 

98 (Usually .dump files do not contain type to species mapping.) 

99 prismobj : Prism 

100 Coordinate transformation between LAMMPS and ASE. 

101 units : str 

102 LAMMPS units for unit transformation between LAMMPS and ASE. 

103 

104 Returns 

105 ------- 

106 :class:`~ase.Atoms` 

107 

108 """ 

109 # read IDs if given and order if needed 

110 if 'id' in colnames: 

111 ids = data['id'] 

112 if order: 

113 sort_order = np.argsort(ids) 

114 data = data[sort_order] 

115 

116 # determine the elements 

117 if 'element' in colnames: 

118 # priority to elements written in file 

119 elements = data['element'] 

120 elif 'mass' in colnames: 

121 # try to determine elements from masses 

122 elements = [_mass2element(m) for m in data['mass']] 

123 elif 'type' in colnames: 

124 # fall back to `types` otherwise 

125 elements = data['type'] 

126 

127 # reconstruct types from given specorder 

128 if specorder: 

129 elements = [specorder[t - 1] for t in elements] 

130 else: 

131 # todo: what if specorder give but no types? 

132 # in principle the masses could work for atoms, but that needs 

133 # lots of cases and new code I guess 

134 raise ValueError('Cannot determine atom types form LAMMPS dump file') 

135 

136 def get_quantity(labels, quantity=None): 

137 try: 

138 cols = np.column_stack([data[label] for label in labels]) 

139 if quantity: 

140 return convert(cols, quantity, units, 'ASE') 

141 return cols 

142 except ValueError: 

143 return None 

144 

145 # Positions 

146 positions = None 

147 scaled_positions = None 

148 if 'x' in colnames: 

149 # doc: x, y, z = unscaled atom coordinates 

150 positions = get_quantity(['x', 'y', 'z'], 'distance') 

151 elif 'xs' in colnames: 

152 # doc: xs,ys,zs = scaled atom coordinates 

153 scaled_positions = get_quantity(['xs', 'ys', 'zs']) 

154 elif 'xu' in colnames: 

155 # doc: xu,yu,zu = unwrapped atom coordinates 

156 positions = get_quantity(['xu', 'yu', 'zu'], 'distance') 

157 elif 'xsu' in colnames: 

158 # xsu,ysu,zsu = scaled unwrapped atom coordinates 

159 scaled_positions = get_quantity(['xsu', 'ysu', 'zsu']) 

160 else: 

161 raise ValueError('No atomic positions found in LAMMPS output') 

162 

163 velocities = get_quantity(['vx', 'vy', 'vz'], 'velocity') 

164 charges = get_quantity(['q'], 'charge') 

165 forces = get_quantity(['fx', 'fy', 'fz'], 'force') 

166 # !TODO: how need quaternions be converted? 

167 quaternions = get_quantity(['c_q[1]', 'c_q[2]', 'c_q[3]', 'c_q[4]']) 

168 

169 # convert cell 

170 cell = convert(cell, 'distance', units, 'ASE') 

171 celldisp = convert(celldisp, 'distance', units, 'ASE') 

172 if prismobj: 

173 celldisp = prismobj.vector_to_ase(celldisp) 

174 cell = prismobj.update_cell(cell) 

175 

176 if quaternions is not None: 

177 out_atoms = Atoms( 

178 symbols=elements, 

179 positions=positions, 

180 cell=cell, 

181 celldisp=celldisp, 

182 pbc=pbc, 

183 ) 

184 out_atoms.new_array('quaternions', quaternions, dtype=float) 

185 elif positions is not None: 

186 # reverse coordinations transform to lammps system 

187 # (for all vectors = pos, vel, force) 

188 if prismobj: 

189 positions = prismobj.vector_to_ase(positions, wrap=True) 

190 

191 out_atoms = Atoms( 

192 symbols=elements, 

193 positions=positions, 

194 pbc=pbc, 

195 celldisp=celldisp, 

196 cell=cell, 

197 ) 

198 elif scaled_positions is not None: 

199 out_atoms = Atoms( 

200 symbols=elements, 

201 scaled_positions=scaled_positions, 

202 pbc=pbc, 

203 celldisp=celldisp, 

204 cell=cell, 

205 ) 

206 else: 

207 raise RuntimeError('No atomsobj created from LAMMPS data!') 

208 

209 if velocities is not None: 

210 if prismobj: 

211 velocities = prismobj.vector_to_ase(velocities) 

212 out_atoms.set_velocities(velocities) 

213 if charges is not None: 

214 out_atoms.set_initial_charges([charge[0] for charge in charges]) 

215 if forces is not None: 

216 if prismobj: 

217 forces = prismobj.vector_to_ase(forces) 

218 # !TODO: use another calculator if available (or move forces 

219 # to atoms.property) (other problem: synchronizing 

220 # parallel runs) 

221 calculator = SinglePointCalculator(out_atoms, energy=0.0, forces=forces) 

222 out_atoms.calc = calculator 

223 

224 # process the extra columns of fixes, variables and computes 

225 # that can be dumped, add as additional arrays to atoms object 

226 for colname in colnames: 

227 # determine if it is a compute, fix or 

228 # custom property/atom (but not the quaternian) 

229 if ( 

230 colname.startswith('f_') 

231 or colname.startswith('v_') 

232 or colname.startswith('d_') 

233 or colname.startswith('d2_') 

234 or (colname.startswith('c_') and not colname.startswith('c_q[')) 

235 ): 

236 out_atoms.new_array(colname, data[colname], dtype='float') 

237 

238 elif colname.startswith('i_') or colname.startswith('i2_'): 

239 out_atoms.new_array(colname, data[colname], dtype='int') 

240 elif colname == 'type': 

241 try: 

242 out_atoms.new_array(colname, data['type'], dtype='int') 

243 except ValueError: 

244 pass # in case type is not integer 

245 

246 return out_atoms 

247 

248 

249def construct_cell(diagdisp, offdiag): 

250 """Help function to create an ASE-cell with displacement vector from 

251 the lammps coordination system parameters. 

252 

253 Parameters 

254 ---------- 

255 diagdisp : np.ndarray 

256 Cell dimension convoluted with the displacement vector. 

257 offdiag : np.ndarray 

258 Off-diagonal cell elements. 

259 

260 Returns 

261 ------- 

262 tuple[np.ndarray, np.ndarray] 

263 Cell and cell displacement vector. 

264 

265 """ 

266 xlo, xhi, ylo, yhi, zlo, zhi = diagdisp 

267 xy, xz, yz = offdiag 

268 

269 # create ase-cell from lammps-box 

270 xhilo = (xhi - xlo) - abs(xy) - abs(xz) 

271 yhilo = (yhi - ylo) - abs(yz) 

272 zhilo = zhi - zlo 

273 celldispx = xlo - min(0, xy) - min(0, xz) 

274 celldispy = ylo - min(0, yz) 

275 celldispz = zlo 

276 cell = np.array([[xhilo, 0, 0], [xy, yhilo, 0], [xz, yz, zhilo]]) 

277 celldisp = np.array([celldispx, celldispy, celldispz]) 

278 

279 return cell, celldisp 

280 

281 

282def _parse_pbc(tilt_items: list[str]) -> list[bool]: 

283 """Handle pbc conditions.""" 

284 pbc_items = tilt_items[-3:] if len(tilt_items) >= 3 else ['f', 'f', 'f'] 

285 return ['p' in d.lower() for d in pbc_items] 

286 

287 

288def _parse_box_bound(line: str, cell_lines: list[str]) -> tuple: 

289 # save labels behind "ITEM: BOX BOUNDS" in triclinic case 

290 # (>=lammps-7Jul09) 

291 tilt_items = line.split()[3:] 

292 cell_data = np.loadtxt(cell_lines) 

293 

294 # general triclinic boxes (>=patch_17Apr2024) 

295 if tilt_items[0] == 'abc': 

296 cell = cell_data[:, :3] 

297 celldisp = cell_data[:, 3] 

298 pbc = _parse_pbc(tilt_items) 

299 return cell, celldisp, pbc 

300 

301 diagdisp = cell_data[:, :2].flatten() 

302 

303 # determine cell tilt (triclinic case!) 

304 if len(cell_data[0]) > 2: 

305 # for >=lammps-7Jul09 use labels behind "ITEM: BOX BOUNDS" 

306 # to assign tilt (vector) elements ... 

307 offdiag = cell_data[:, 2] 

308 # ... otherwise assume default order in 3rd column 

309 # (if the latter was present) 

310 if len(tilt_items) >= 3: 

311 sort_index = [tilt_items.index(i) for i in ['xy', 'xz', 'yz']] 

312 offdiag = offdiag[sort_index] 

313 else: 

314 offdiag = np.zeros(3) 

315 

316 cell, celldisp = construct_cell(diagdisp, offdiag) 

317 

318 pbc = _parse_pbc(tilt_items) 

319 

320 return cell, celldisp, pbc 

321 

322 

323def _colnames2dtypes(colnames: list[str]) -> list[tuple[str, Any]]: 

324 # Determine the data types for each column 

325 dtype: list[tuple[str, Any]] = [] 

326 for colname in colnames: 

327 if ( 

328 colname in {'id', 'type'} 

329 or colname.startswith('i_') 

330 or colname.startswith('i2_') 

331 ): 

332 dtype.append((colname, int)) 

333 elif colname == 'element': 

334 # 'U10' for strings with a max length of 10 characters 

335 dtype.append((colname, 'U10')) 

336 else: 

337 dtype.append((colname, float)) 

338 return dtype 

339 

340 

341def _read_lammps_dump_text_frame(fd: TextIO, n: int, **kwargs) -> Atoms: 

342 # avoid references before assignment in case of incorrect file structure 

343 cell, celldisp, pbc, info = None, None, False, {} 

344 

345 fd.seek(n) # jump to the position just after 'ITEM: TIMESTEP' 

346 line = fd.readline() 

347 info['timestep'] = int(line.split()[0]) 

348 

349 while line := fd.readline(): 

350 if 'ITEM: NUMBER OF ATOMS' in line: 

351 line = fd.readline() 

352 n_atoms = int(line.split()[0]) 

353 

354 if 'ITEM: BOX BOUNDS' in line: 

355 cell_lines = [fd.readline() for _ in range(3)] 

356 cell, celldisp, pbc = _parse_box_bound(line, cell_lines) 

357 

358 if 'ITEM: ATOMS' in line: 

359 colnames = line.split()[2:] 

360 dtype = _colnames2dtypes(colnames) 

361 datarows = [fd.readline() for _ in range(n_atoms)] 

362 data = np.loadtxt(datarows, dtype=dtype, ndmin=1) 

363 out_atoms = _lammps_data_to_ase_atoms( 

364 data=data, 

365 colnames=colnames, 

366 cell=cell, 

367 celldisp=celldisp, 

368 pbc=pbc, 

369 **kwargs, 

370 ) 

371 out_atoms.info.update(info) 

372 return out_atoms 

373 

374 raise RuntimeError('Incomplete LAMMPS dump text chunk') 

375 

376 

377class _LAMMPSDumpTextChunk(ImageChunk): 

378 def __init__(self, fd: TextIO, pos: int) -> None: 

379 self.fd = fd 

380 self.pos = pos 

381 

382 def build(self, **kwargs) -> Atoms: 

383 return _read_lammps_dump_text_frame(self.fd, self.pos, **kwargs) 

384 

385 

386def _i_lammps_dump_text_chunks(fd: TextIO) -> Iterator[_LAMMPSDumpTextChunk]: 

387 while line := fd.readline(): 

388 if 'ITEM: TIMESTEP' in line: 

389 pos = fd.tell() # position just after 'ITEM: TIMESTEP' 

390 yield _LAMMPSDumpTextChunk(fd, pos) 

391 

392 

393iread_lammps_dump_text = ImageIterator(_i_lammps_dump_text_chunks) 

394 

395 

396@reader 

397def read_lammps_dump_text(fd, index=-1, **kwargs): 

398 """Read a LAMMPS text dump file.""" 

399 g = iread_lammps_dump_text(fd, index=index, **kwargs) 

400 return list(g) if isinstance(index, (slice, str)) else next(g) 

401 

402 

403def _read_lammps_dump_binary_data(fd, /, colnames=None, intformat='SMALLBIG'): 

404 # depending on the chosen compilation flag lammps uses either normal 

405 # integers or long long for its id or timestep numbering 

406 # !TODO: tags are cast to double -> missing/double ids (add check?) 

407 _tagformat, bigformat = { 

408 'SMALLSMALL': ('i', 'i'), 

409 'SMALLBIG': ('i', 'q'), 

410 'BIGBIG': ('q', 'q'), 

411 }[intformat] 

412 

413 # wrap struct.unpack to raise EOFError 

414 def read_variables(string): 

415 obj_len = struct.calcsize(string) 

416 data_obj = fd.read(obj_len) 

417 if obj_len != len(data_obj): 

418 raise EOFError 

419 return struct.unpack(string, data_obj) 

420 

421 # Assume that the binary dump file is in the old (pre-29Oct2020) 

422 # format 

423 magic_string = None 

424 

425 # read header 

426 (ntimestep,) = read_variables('=' + bigformat) 

427 

428 # In the new LAMMPS binary dump format (version 29Oct2020 and 

429 # onward), a negative timestep is used to indicate that the next 

430 # few bytes will contain certain metadata 

431 if ntimestep < 0: 

432 # First bigint was actually encoding the negative of the format 

433 # name string length (we call this 'magic_string' to 

434 magic_string_len = -ntimestep 

435 

436 # The next `magic_string_len` bytes will hold a string 

437 # indicating the format of the dump file 

438 magic_string = b''.join( 

439 read_variables('=' + str(magic_string_len) + 'c') 

440 ) 

441 

442 # Read endianness (integer). For now, we'll disregard the value 

443 # and simply use the host machine's endianness (via '=' 

444 # character used with struct.calcsize). 

445 # 

446 # TODO: Use the endianness of the dump file in subsequent 

447 # read_variables rather than just assuming it will match 

448 # that of the host 

449 read_variables('=i') 

450 

451 # Read revision number (integer) 

452 (revision,) = read_variables('=i') 

453 

454 # Finally, read the actual timestep (bigint) 

455 (ntimestep,) = read_variables('=' + bigformat) 

456 

457 _n_atoms, triclinic = read_variables('=' + bigformat + 'i') 

458 boundary = read_variables('=6i') 

459 

460 if triclinic == 0: 

461 diagdisp = read_variables('=6d') 

462 offdiag = (0.0,) * 3 

463 cell, celldisp = construct_cell(diagdisp, offdiag) 

464 elif triclinic == 1: 

465 diagdisp = read_variables('=6d') 

466 offdiag = read_variables('=3d') 

467 cell, celldisp = construct_cell(diagdisp, offdiag) 

468 elif triclinic == 2: # general triclinic boxes (>=patch_17Apr2024) 

469 cell = np.array(read_variables('=9d')).reshape(3, 3) 

470 celldisp = np.array(read_variables('=3d')) 

471 else: 

472 raise ValueError(triclinic) 

473 

474 (size_one,) = read_variables('=i') 

475 

476 if len(colnames) != size_one: 

477 raise ValueError('Provided columns do not match binary file') 

478 

479 if magic_string and revision > 1: 

480 # New binary dump format includes units string, 

481 # columns string, and time 

482 (units_str_len,) = read_variables('=i') 

483 

484 if units_str_len > 0: 

485 # Read lammps units style 

486 _ = b''.join(read_variables('=' + str(units_str_len) + 'c')) 

487 

488 (flag,) = read_variables('=c') 

489 if flag != b'\x00': 

490 # Flag was non-empty string 

491 read_variables('=d') 

492 

493 # Length of column string 

494 (columns_str_len,) = read_variables('=i') 

495 

496 # Read column string (e.g., "id type x y z vx vy vz fx fy fz") 

497 _ = b''.join(read_variables('=' + str(columns_str_len) + 'c')) 

498 

499 (nchunk,) = read_variables('=i') 

500 

501 # lammps cells/boxes can have different boundary conditions on each 

502 # sides (makes mainly sense for different non-periodic conditions 

503 # (e.g. [f]ixed and [s]hrink for a irradiation simulation)) 

504 # periodic case: b 0 = 'p' 

505 # non-peridic cases 1: 'f', 2 : 's', 3: 'm' 

506 pbc = np.sum(np.array(boundary).reshape((3, 2)), axis=1) == 0 

507 

508 data = [] 

509 for _ in range(nchunk): 

510 # number-of-data-entries 

511 (n_data,) = read_variables('=i') 

512 # retrieve per atom data 

513 data += read_variables('=' + str(n_data) + 'd') 

514 

515 return data, cell, celldisp, pbc 

516 

517 

518class _LAMMPSDumpBinaryChunk(ImageChunk): 

519 def __init__( 

520 self, 

521 fd: IO, 

522 colnames: list[str] | None, 

523 intformat: str, 

524 ) -> None: 

525 # Standard columns layout from lammpsrun 

526 colnames_default = [ 

527 'id', 

528 'type', 

529 'x', 

530 'y', 

531 'z', 

532 'vx', 

533 'vy', 

534 'vz', 

535 'fx', 

536 'fy', 

537 'fz', 

538 ] 

539 self.colnames = colnames if colnames else colnames_default 

540 

541 _ = _read_lammps_dump_binary_data(fd, self.colnames, intformat) 

542 self.data = _[0] 

543 self.cell = _[1] 

544 self.celldisp = _[2] 

545 self.pbc = _[3] 

546 

547 def build(self, **kwargs) -> Atoms: 

548 data = np.array(self.data).reshape((-1, len(self.colnames))) 

549 

550 # convert the 2D float array to the structured array 

551 dtype = _colnames2dtypes(self.colnames) 

552 data = np.rec.fromarrays(data.T, dtype=dtype) 

553 

554 # map data-chunk to ase atoms 

555 return _lammps_data_to_ase_atoms( 

556 data=data, 

557 colnames=self.colnames, 

558 cell=self.cell, 

559 celldisp=self.celldisp, 

560 pbc=self.pbc, 

561 **kwargs, 

562 ) 

563 

564 

565class _LAMMPSDumpBinaryChunkIterator: 

566 def __init__(self) -> None: 

567 self.colnames = None 

568 self.intformat = '' 

569 

570 def __call__(self, fd: IO) -> Iterator[_LAMMPSDumpBinaryChunk]: 

571 while True: 

572 try: 

573 yield _LAMMPSDumpBinaryChunk(fd, self.colnames, self.intformat) 

574 except EOFError: 

575 break 

576 

577 

578class _LAMMPSDumpBinaryImageIterator(ImageIterator): 

579 def __call__(self, fd: IO, index=None, **kwargs) -> Iterator[Atoms]: 

580 _kwargs = kwargs.copy() 

581 self.ichunks: _LAMMPSDumpBinaryChunkIterator 

582 self.ichunks.colnames = _kwargs.pop('colnames', None) 

583 self.ichunks.intformat = _kwargs.pop('intformat', 'SMALLBIG') 

584 return super().__call__(fd, index, **_kwargs) 

585 

586 

587iread_lammps_dump_binary = _LAMMPSDumpBinaryImageIterator( 

588 _LAMMPSDumpBinaryChunkIterator() 

589) 

590 

591 

592def read_lammps_dump_binary(fd, /, index=-1, **kwargs): 

593 """Read binary dump-files (after binary2txt.cpp from lammps/tools). 

594 

595 Parameters 

596 ---------- 

597 fileobj : IOBase 

598 File-stream containing the binary lammps data. 

599 index : int | slice, default: -1 

600 Index of the configuration. 

601 colnames : list[str] 

602 Column names to parse. 

603 intformat : Literal['SMALLSMALL', 'SMALLBIG', 'BIGBIG'] 

604 Integer size in LAMMPS. This is set at compile-time and can 

605 unfortunately not derived from data file. 

606 

607 Returns 

608 ------- 

609 Atoms | list[Atoms] 

610 

611 """ 

612 g = iread_lammps_dump_binary(fd, index=index, **kwargs) 

613 return list(g) if isinstance(index, (slice, str)) else next(g) 

614 

615 

616def _mass2element(mass): 

617 """ 

618 Guess the element corresponding to a given atomic mass. 

619 

620 Parameters 

621 ---------- 

622 mass : float 

623 Atomic mass for searching. 

624 

625 Returns 

626 ------- 

627 str 

628 Element symbol as a string. 

629 

630 """ 

631 min_idx = np.argmin(np.abs(atomic_masses - mass)) 

632 element = chemical_symbols[min_idx] 

633 return element