Coverage for ase/io/opls.py: 53.98%

502 statements  

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

1import time 

2 

3import numpy as np 

4 

5from ase.atom import Atom 

6from ase.atoms import Atoms 

7from ase.calculators.lammpsrun import Prism 

8from ase.data import atomic_masses, chemical_symbols 

9from ase.io import read 

10from ase.neighborlist import NeighborList 

11 

12 

13def twochar(name): 

14 if len(name) > 1: 

15 return name[:2] 

16 else: 

17 return name + ' ' 

18 

19 

20class BondData: 

21 def __init__(self, name_value_hash): 

22 self.nvh = name_value_hash 

23 

24 def name_value(self, aname, bname): 

25 name1 = twochar(aname) + '-' + twochar(bname) 

26 name2 = twochar(bname) + '-' + twochar(aname) 

27 if name1 in self.nvh: 

28 return name1, self.nvh[name1] 

29 if name2 in self.nvh: 

30 return name2, self.nvh[name2] 

31 return None, None 

32 

33 def value(self, aname, bname): 

34 return self.name_value(aname, bname)[1] 

35 

36 

37class CutoffList(BondData): 

38 def max(self): 

39 return max(self.nvh.values()) 

40 

41 

42class AnglesData: 

43 def __init__(self, name_value_hash): 

44 self.nvh = name_value_hash 

45 

46 def name_value(self, aname, bname, cname): 

47 for name in [ 

48 (twochar(aname) + '-' + twochar(bname) + '-' + twochar(cname)), 

49 (twochar(cname) + '-' + twochar(bname) + '-' + twochar(aname)), 

50 ]: 

51 if name in self.nvh: 

52 return name, self.nvh[name] 

53 return None, None 

54 

55 

56class DihedralsData: 

57 def __init__(self, name_value_hash): 

58 self.nvh = name_value_hash 

59 

60 def name_value(self, aname, bname, cname, dname): 

61 for name in [ 

62 ( 

63 twochar(aname) 

64 + '-' 

65 + twochar(bname) 

66 + '-' 

67 + twochar(cname) 

68 + '-' 

69 + twochar(dname) 

70 ), 

71 ( 

72 twochar(dname) 

73 + '-' 

74 + twochar(cname) 

75 + '-' 

76 + twochar(bname) 

77 + '-' 

78 + twochar(aname) 

79 ), 

80 ]: 

81 if name in self.nvh: 

82 return name, self.nvh[name] 

83 return None, None 

84 

85 

86class OPLSff: 

87 """OPLS helper class. 

88 Read OPLS structure and force field parameters and write LAMMPS input. 

89 """ 

90 

91 def __init__(self, fileobj=None, warnings=0): 

92 self.warnings = warnings 

93 self.data = {} 

94 if fileobj is not None: 

95 self.read(fileobj) 

96 

97 def read(self, fileobj, comments='#'): 

98 

99 def read_block(name, symlen, nvalues): 

100 """Read a data block. 

101 

102 name: name of the block to store in self.data 

103 symlen: length of the symbol 

104 nvalues: number of values expected 

105 """ 

106 

107 if name not in self.data: 

108 self.data[name] = {} 

109 data = self.data[name] 

110 

111 def add_line(): 

112 line = fileobj.readline().strip() 

113 if not len(line): # end of the block 

114 return False 

115 line = line.split('#')[0] # get rid of comments 

116 if len(line) > symlen: 

117 symbol = line[:symlen] 

118 words = line[symlen:].split() 

119 if len(words) >= nvalues: 

120 if nvalues == 1: 

121 data[symbol] = float(words[0]) 

122 else: 

123 data[symbol] = [ 

124 float(word) for word in words[:nvalues] 

125 ] 

126 return True 

127 

128 while add_line(): 

129 pass 

130 

131 read_block('one', 2, 3) 

132 read_block('bonds', 5, 2) 

133 read_block('angles', 8, 2) 

134 read_block('dihedrals', 11, 4) 

135 read_block('cutoffs', 5, 1) 

136 

137 self.bonds = BondData(self.data['bonds']) 

138 self.angles = AnglesData(self.data['angles']) 

139 self.dihedrals = DihedralsData(self.data['dihedrals']) 

140 self.cutoffs = CutoffList(self.data['cutoffs']) 

141 

142 def write_lammps(self, atoms, prefix='lammps'): 

143 """Write input for a LAMMPS calculation.""" 

144 self.prefix = prefix 

145 

146 if hasattr(atoms, 'connectivities'): 

147 connectivities = atoms.connectivities 

148 else: 

149 btypes, blist = self.get_bonds(atoms) 

150 atypes, alist = self.get_angles() 

151 dtypes, dlist = self.get_dihedrals(alist, atypes) 

152 connectivities = { 

153 'bonds': blist, 

154 'bond types': btypes, 

155 'angles': alist, 

156 'angle types': atypes, 

157 'dihedrals': dlist, 

158 'dihedral types': dtypes, 

159 } 

160 

161 self.write_lammps_definitions(atoms, btypes, atypes, dtypes) 

162 self.write_lammps_in() 

163 

164 self.write_lammps_atoms(atoms, connectivities) 

165 

166 def write_lammps_in(self): 

167 with open(self.prefix + '_in', 'w') as fileobj: 

168 self._write_lammps_in(fileobj) 

169 

170 def _write_lammps_in(self, fileobj): 

171 fileobj.write("""# LAMMPS relaxation (written by ASE) 

172 

173units metal 

174atom_style full 

175boundary p p p 

176#boundary p p f 

177 

178""") 

179 fileobj.write('read_data ' + self.prefix + '_atoms\n') 

180 fileobj.write('include ' + self.prefix + '_opls\n') 

181 fileobj.write(""" 

182kspace_style pppm 1e-5 

183#kspace_modify slab 3.0 

184 

185neighbor 1.0 bin 

186neigh_modify delay 0 every 1 check yes 

187 

188thermo 1000 

189thermo_style custom step temp press cpu pxx pyy pzz pxy pxz pyz ke pe etotal vol lx ly lz atoms 

190 

191dump 1 all xyz 1000 dump_relax.xyz 

192dump_modify 1 sort id 

193 

194restart 100000 test_relax 

195 

196min_style fire 

197minimize 1.0e-14 1.0e-5 100000 100000 

198""") # noqa: E501 

199 

200 def write_lammps_atoms(self, atoms, connectivities): 

201 """Write atoms input for LAMMPS""" 

202 with open(self.prefix + '_atoms', 'w') as fileobj: 

203 self._write_lammps_atoms(fileobj, atoms, connectivities) 

204 

205 def _write_lammps_atoms(self, fileobj, atoms, connectivities): 

206 # header 

207 fileobj.write(fileobj.name + ' (by ' + str(self.__class__) + ')\n\n') 

208 fileobj.write(str(len(atoms)) + ' atoms\n') 

209 fileobj.write(str(len(atoms.types)) + ' atom types\n') 

210 blist = connectivities['bonds'] 

211 if len(blist): 

212 btypes = connectivities['bond types'] 

213 fileobj.write(str(len(blist)) + ' bonds\n') 

214 fileobj.write(str(len(btypes)) + ' bond types\n') 

215 alist = connectivities['angles'] 

216 if len(alist): 

217 atypes = connectivities['angle types'] 

218 fileobj.write(str(len(alist)) + ' angles\n') 

219 fileobj.write(str(len(atypes)) + ' angle types\n') 

220 dlist = connectivities['dihedrals'] 

221 if len(dlist): 

222 dtypes = connectivities['dihedral types'] 

223 fileobj.write(str(len(dlist)) + ' dihedrals\n') 

224 fileobj.write(str(len(dtypes)) + ' dihedral types\n') 

225 

226 # cell 

227 p = Prism(atoms.get_cell()) 

228 xhi, yhi, zhi, xy, xz, yz = p.get_lammps_prism() 

229 fileobj.write(f'\n0.0 {xhi} xlo xhi\n') 

230 fileobj.write(f'0.0 {yhi} ylo yhi\n') 

231 fileobj.write(f'0.0 {zhi} zlo zhi\n') 

232 

233 if p.is_skewed(): 

234 fileobj.write(f'{xy} {xz} {yz} xy xz yz\n') 

235 

236 # atoms 

237 fileobj.write('\nAtoms\n\n') 

238 tag = atoms.get_tags() 

239 if atoms.has('molid'): 

240 molid = atoms.get_array('molid') 

241 else: 

242 molid = [1] * len(atoms) 

243 for i, r in enumerate(p.vector_to_lammps(atoms.get_positions())): 

244 atype = atoms.types[tag[i]] 

245 if len(atype) < 2: 

246 atype = atype + ' ' 

247 q = self.data['one'][atype][2] 

248 fileobj.write( 

249 '%6d %3d %3d %s %s %s %s' 

250 % ((i + 1, molid[i], tag[i] + 1, q) + tuple(r)) 

251 ) 

252 fileobj.write(' # ' + atoms.types[tag[i]] + '\n') 

253 

254 # velocities 

255 velocities = atoms.get_velocities() 

256 if velocities is not None: 

257 velocities = p.vector_to_lammps(atoms.get_velocities()) 

258 fileobj.write('\nVelocities\n\n') 

259 for i, v in enumerate(velocities): 

260 fileobj.write('%6d %g %g %g\n' % (i + 1, v[0], v[1], v[2])) 

261 

262 # masses 

263 fileobj.write('\nMasses\n\n') 

264 for i, typ in enumerate(atoms.types): 

265 cs = atoms.split_symbol(typ)[0] 

266 fileobj.write( 

267 '%6d %g # %s -> %s\n' 

268 % (i + 1, atomic_masses[chemical_symbols.index(cs)], typ, cs) 

269 ) 

270 

271 # bonds 

272 if blist: 

273 fileobj.write('\nBonds\n\n') 

274 for ib, bvals in enumerate(blist): 

275 fileobj.write( 

276 '%8d %6d %6d %6d ' 

277 % (ib + 1, bvals[0] + 1, bvals[1] + 1, bvals[2] + 1) 

278 ) 

279 if bvals[0] in btypes: 

280 fileobj.write('# ' + btypes[bvals[0]]) 

281 fileobj.write('\n') 

282 

283 # angles 

284 if alist: 

285 fileobj.write('\nAngles\n\n') 

286 for ia, avals in enumerate(alist): 

287 fileobj.write( 

288 '%8d %6d %6d %6d %6d ' 

289 % ( 

290 ia + 1, 

291 avals[0] + 1, 

292 avals[1] + 1, 

293 avals[2] + 1, 

294 avals[3] + 1, 

295 ) 

296 ) 

297 if avals[0] in atypes: 

298 fileobj.write('# ' + atypes[avals[0]]) 

299 fileobj.write('\n') 

300 

301 # dihedrals 

302 if dlist: 

303 fileobj.write('\nDihedrals\n\n') 

304 for i, dvals in enumerate(dlist): 

305 fileobj.write( 

306 '%8d %6d %6d %6d %6d %6d ' 

307 % ( 

308 i + 1, 

309 dvals[0] + 1, 

310 dvals[1] + 1, 

311 dvals[2] + 1, 

312 dvals[3] + 1, 

313 dvals[4] + 1, 

314 ) 

315 ) 

316 if dvals[0] in dtypes: 

317 fileobj.write('# ' + dtypes[dvals[0]]) 

318 fileobj.write('\n') 

319 

320 def update_neighbor_list(self, atoms): 

321 cut = 0.5 * max(self.data['cutoffs'].values()) 

322 self.nl = NeighborList( 

323 [cut] * len(atoms), skin=0, bothways=True, self_interaction=False 

324 ) 

325 self.nl.update(atoms) 

326 self.atoms = atoms 

327 

328 def get_bonds(self, atoms): 

329 """Find bonds and return them and their types""" 

330 cutoffs = CutoffList(self.data['cutoffs']) 

331 self.update_neighbor_list(atoms) 

332 

333 types = atoms.get_types() 

334 tags = atoms.get_tags() 

335 cell = atoms.get_cell() 

336 bond_list = [] 

337 bond_types = [] 

338 for i, atom in enumerate(atoms): 

339 iname = types[tags[i]] 

340 indices, offsets = self.nl.get_neighbors(i) 

341 for j, offset in zip(indices, offsets): 

342 if j <= i: 

343 continue # do not double count 

344 jname = types[tags[j]] 

345 cut = cutoffs.value(iname, jname) 

346 if cut is None: 

347 if self.warnings > 1: 

348 print(f'Warning: cutoff {iname}-{jname} not found') 

349 continue # don't have it 

350 dist = np.linalg.norm( 

351 atom.position - atoms[j].position - np.dot(offset, cell) 

352 ) 

353 if dist > cut: 

354 continue # too far away 

355 name, _val = self.bonds.name_value(iname, jname) 

356 if name is None: 

357 if self.warnings: 

358 print(f'Warning: potential {iname}-{jname} not found') 

359 continue # don't have it 

360 if name not in bond_types: 

361 bond_types.append(name) 

362 bond_list.append([bond_types.index(name), i, j]) 

363 return bond_types, bond_list 

364 

365 def get_angles(self, atoms=None): 

366 cutoffs = CutoffList(self.data['cutoffs']) 

367 if atoms is not None: 

368 self.update_neighbor_list(atoms) 

369 else: 

370 atoms = self.atoms 

371 

372 types = atoms.get_types() 

373 tags = atoms.get_tags() 

374 cell = atoms.get_cell() 

375 ang_list = [] 

376 ang_types = [] 

377 

378 # center atom *-i-* 

379 for i, atom in enumerate(atoms): 

380 iname = types[tags[i]] 

381 indicesi, offsetsi = self.nl.get_neighbors(i) 

382 

383 # search for first neighbor j-i-* 

384 for j, offsetj in zip(indicesi, offsetsi): 

385 jname = types[tags[j]] 

386 cut = cutoffs.value(iname, jname) 

387 if cut is None: 

388 continue # don't have it 

389 dist = np.linalg.norm( 

390 atom.position - atoms[j].position - np.dot(offsetj, cell) 

391 ) 

392 if dist > cut: 

393 continue # too far away 

394 

395 # search for second neighbor j-i-k 

396 for k, offsetk in zip(indicesi, offsetsi): 

397 if k <= j: 

398 continue # avoid double count 

399 kname = types[tags[k]] 

400 cut = cutoffs.value(iname, kname) 

401 if cut is None: 

402 continue # don't have it 

403 dist = np.linalg.norm( 

404 atom.position 

405 - np.dot(offsetk, cell) 

406 - atoms[k].position 

407 ) 

408 if dist > cut: 

409 continue # too far away 

410 name, _val = self.angles.name_value(jname, iname, kname) 

411 if name is None: 

412 if self.warnings > 1: 

413 print( 

414 f'Warning: angles {jname}-{iname}-{kname} not ' 

415 'found' 

416 ) 

417 continue # don't have it 

418 if name not in ang_types: 

419 ang_types.append(name) 

420 ang_list.append([ang_types.index(name), j, i, k]) 

421 

422 return ang_types, ang_list 

423 

424 def get_dihedrals(self, ang_types, ang_list): 

425 "Dihedrals derived from angles." 

426 

427 cutoffs = CutoffList(self.data['cutoffs']) 

428 

429 atoms = self.atoms 

430 types = atoms.get_types() 

431 tags = atoms.get_tags() 

432 cell = atoms.get_cell() 

433 

434 dih_list = [] 

435 dih_types = [] 

436 

437 def append(name, i, j, k, L): 

438 if name not in dih_types: 

439 dih_types.append(name) 

440 index = dih_types.index(name) 

441 if ([index, i, j, k, L] not in dih_list) and ( 

442 [index, L, k, j, i] not in dih_list 

443 ): 

444 dih_list.append([index, i, j, k, L]) 

445 

446 for angle in ang_types: 

447 L, i, j, k = angle 

448 iname = types[tags[i]] 

449 jname = types[tags[j]] 

450 kname = types[tags[k]] 

451 

452 # search for l-i-j-k 

453 indicesi, offsetsi = self.nl.get_neighbors(i) 

454 for L, offsetl in zip(indicesi, offsetsi): 

455 if L == j: 

456 continue # avoid double count 

457 lname = types[tags[L]] 

458 cut = cutoffs.value(iname, lname) 

459 if cut is None: 

460 continue # don't have it 

461 dist = np.linalg.norm( 

462 atoms[i].position 

463 - atoms[L].position 

464 - np.dot(offsetl, cell) 

465 ) 

466 if dist > cut: 

467 continue # too far away 

468 name, _val = self.dihedrals.name_value( 

469 lname, iname, jname, kname 

470 ) 

471 if name is None: 

472 continue # don't have it 

473 append(name, L, i, j, k) 

474 

475 # search for i-j-k-l 

476 indicesk, offsetsk = self.nl.get_neighbors(k) 

477 for L, offsetl in zip(indicesk, offsetsk): 

478 if L == j: 

479 continue # avoid double count 

480 lname = types[tags[L]] 

481 cut = cutoffs.value(kname, lname) 

482 if cut is None: 

483 continue # don't have it 

484 dist = np.linalg.norm( 

485 atoms[k].position 

486 - atoms[L].position 

487 - np.dot(offsetl, cell) 

488 ) 

489 if dist > cut: 

490 continue # too far away 

491 name, _val = self.dihedrals.name_value( 

492 iname, jname, kname, lname 

493 ) 

494 if name is None: 

495 continue # don't have it 

496 append(name, i, j, k, L) 

497 

498 return dih_types, dih_list 

499 

500 def write_lammps_definitions(self, atoms, btypes, atypes, dtypes): 

501 """Write force field definitions for LAMMPS.""" 

502 with open(self.prefix + '_opls', 'w') as fd: 

503 self._write_lammps_definitions(fd, atoms, btypes, atypes, dtypes) 

504 

505 def _write_lammps_definitions(self, fileobj, atoms, btypes, atypes, dtypes): 

506 fileobj.write('# OPLS potential\n') 

507 fileobj.write( 

508 '# write_lammps' + str(time.asctime(time.localtime(time.time()))) 

509 ) 

510 

511 # bonds 

512 if len(btypes): 

513 fileobj.write('\n# bonds\n') 

514 fileobj.write('bond_style harmonic\n') 

515 for ib, btype in enumerate(btypes): 

516 fileobj.write('bond_coeff %6d' % (ib + 1)) 

517 for value in self.bonds.nvh[btype]: 

518 fileobj.write(' ' + str(value)) 

519 fileobj.write(' # ' + btype + '\n') 

520 

521 # angles 

522 if len(atypes): 

523 fileobj.write('\n# angles\n') 

524 fileobj.write('angle_style harmonic\n') 

525 for ia, atype in enumerate(atypes): 

526 fileobj.write('angle_coeff %6d' % (ia + 1)) 

527 for value in self.angles.nvh[atype]: 

528 fileobj.write(' ' + str(value)) 

529 fileobj.write(' # ' + atype + '\n') 

530 

531 # dihedrals 

532 if len(dtypes): 

533 fileobj.write('\n# dihedrals\n') 

534 fileobj.write('dihedral_style opls\n') 

535 for i, dtype in enumerate(dtypes): 

536 fileobj.write('dihedral_coeff %6d' % (i + 1)) 

537 for value in self.dihedrals.nvh[dtype]: 

538 fileobj.write(' ' + str(value)) 

539 fileobj.write(' # ' + dtype + '\n') 

540 

541 # Lennard Jones settings 

542 fileobj.write('\n# L-J parameters\n') 

543 fileobj.write( 

544 'pair_style lj/cut/coul/long 10.0 7.4' 

545 + ' # consider changing these parameters\n' 

546 ) 

547 fileobj.write('special_bonds lj/coul 0.0 0.0 0.5\n') 

548 data = self.data['one'] 

549 for ia, atype in enumerate(atoms.types): 

550 if len(atype) < 2: 

551 atype = atype + ' ' 

552 fileobj.write('pair_coeff ' + str(ia + 1) + ' ' + str(ia + 1)) 

553 for value in data[atype][:2]: 

554 fileobj.write(' ' + str(value)) 

555 fileobj.write(' # ' + atype + '\n') 

556 fileobj.write('pair_modify shift yes mix geometric\n') 

557 

558 # Charges 

559 fileobj.write('\n# charges\n') 

560 for ia, atype in enumerate(atoms.types): 

561 if len(atype) < 2: 

562 atype = atype + ' ' 

563 fileobj.write('set type ' + str(ia + 1)) 

564 fileobj.write(' charge ' + str(data[atype][2])) 

565 fileobj.write(' # ' + atype + '\n') 

566 

567 

568class OPLSStructure(Atoms): 

569 """Class for representing OPLSSStructure. 

570 

571 Parameters 

572 ---------- 

573 

574 filename: str 

575 Extended xyz filename 

576 

577 """ 

578 

579 default_map = { 

580 'BR': 'Br', 

581 'Be': 'Be', 

582 'C0': 'Ca', 

583 'Li': 'Li', 

584 'Mg': 'Mg', 

585 'Al': 'Al', 

586 'Ar': 'Ar', 

587 } 

588 

589 def __init__(self, filename=None, *args, **kwargs): 

590 Atoms.__init__(self, *args, **kwargs) 

591 if filename: 

592 self.read_extended_xyz(filename) 

593 else: 

594 self.types = [] 

595 for atom in self: 

596 if atom.symbol not in self.types: 

597 self.types.append(atom.symbol) 

598 atom.tag = self.types.index(atom.symbol) 

599 

600 def append(self, atom): 

601 """Append atom to end.""" 

602 self.extend(Atoms([atom])) 

603 

604 def read_extended_xyz(self, fileobj, map=None): 

605 """Read extended xyz file with labeled atoms.""" 

606 if map is None: 

607 map = {} 

608 atoms = read(fileobj) 

609 self.set_cell(atoms.get_cell()) 

610 self.set_pbc(atoms.get_pbc()) 

611 

612 types = [] 

613 types_map = {} 

614 for atom, type in zip(atoms, atoms.get_array('type')): 

615 if type not in types: 

616 types_map[type] = len(types) 

617 types.append(type) 

618 atom.tag = types_map[type] 

619 self.append(atom) 

620 self.types = types 

621 

622 # copy extra array info 

623 for name, array in atoms.arrays.items(): 

624 if name not in self.arrays: 

625 self.new_array(name, array) 

626 

627 def split_symbol(self, string, translate=default_map): 

628 

629 if string in translate: 

630 return translate[string], string 

631 if len(string) < 2: 

632 return string, None 

633 return string[0], string[1] 

634 

635 def get_types(self): 

636 return self.types 

637 

638 def colored(self, elements): 

639 res = Atoms() 

640 res.set_cell(self.get_cell()) 

641 for atom in self: 

642 elem = self.types[atom.tag] 

643 if elem in elements: 

644 elem = elements[elem] 

645 res.append(Atom(elem, atom.position)) 

646 return res 

647 

648 def update_from_lammps_dump(self, fileobj, check=True): 

649 atoms = read(fileobj, format='lammps-dump') 

650 

651 if len(atoms) != len(self): 

652 raise RuntimeError( 

653 'Structure in ' 

654 + str(fileobj) 

655 + ' has wrong length: %d != %d' % (len(atoms), len(self)) 

656 ) 

657 

658 if check: 

659 for a, b in zip(self, atoms): 

660 # check that the atom types match 

661 if a.tag + 1 != b.number: 

662 raise RuntimeError( 

663 'Atoms index %d are of different ' 

664 'type (%d != %d)' % (a.index, a.tag + 1, b.number) 

665 ) 

666 

667 self.set_cell(atoms.get_cell()) 

668 self.set_positions(atoms.get_positions()) 

669 if atoms.get_velocities() is not None: 

670 self.set_velocities(atoms.get_velocities()) 

671 # XXX what about energy and forces ??? 

672 

673 def read_connectivities(self, fileobj, update_types=False): 

674 """Read positions, connectivities, etc. 

675 

676 update_types: update atom types from the masses 

677 """ 

678 lines = fileobj.readlines() 

679 lines.pop(0) 

680 

681 def next_entry(): 

682 line = lines.pop(0).strip() 

683 if len(line) > 0: 

684 lines.insert(0, line) 

685 

686 def next_key(): 

687 while len(lines): 

688 line = lines.pop(0).strip() 

689 if len(line) > 0: 

690 lines.pop(0) 

691 return line 

692 return None 

693 

694 next_entry() 

695 header = {} 

696 while True: 

697 line = lines.pop(0).strip() 

698 if len(line): 

699 w = line.split() 

700 if len(w) == 2: 

701 header[w[1]] = int(w[0]) 

702 else: 

703 header[w[1] + ' ' + w[2]] = int(w[0]) 

704 else: 

705 break 

706 

707 while not lines.pop(0).startswith('Atoms'): 

708 pass 

709 lines.pop(0) 

710 

711 natoms = len(self) 

712 positions = np.empty((natoms, 3)) 

713 for i in range(natoms): 

714 w = lines.pop(0).split() 

715 assert int(w[0]) == (i + 1) 

716 positions[i] = np.array([float(w[4 + c]) for c in range(3)]) 

717 # print(w, positions[i]) 

718 

719 key = next_key() 

720 

721 velocities = None 

722 if key == 'Velocities': 

723 velocities = np.empty((natoms, 3)) 

724 for i in range(natoms): 

725 w = lines.pop(0).split() 

726 assert int(w[0]) == (i + 1) 

727 velocities[i] = np.array([float(w[1 + c]) for c in range(3)]) 

728 key = next_key() 

729 

730 if key == 'Masses': 

731 ntypes = len(self.types) 

732 masses = np.empty(ntypes) 

733 for i in range(ntypes): 

734 w = lines.pop(0).split() 

735 assert int(w[0]) == (i + 1) 

736 masses[i] = float(w[1]) 

737 

738 if update_types: 

739 # get the elements from the masses 

740 # this ensures that we have the right elements 

741 # even when reading from a lammps dump file 

742 def newtype(element, types): 

743 if len(element) > 1: 

744 # can not extend, we are restricted to 

745 # two characters 

746 return element 

747 count = 0 

748 for type in types: 

749 if type[0] == element: 

750 count += 1 

751 label = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' 

752 return element + label[count] 

753 

754 symbolmap = {} 

755 typemap = {} 

756 types = [] 

757 ams = atomic_masses[:] 

758 ams[np.isnan(ams)] = 0 

759 for i, mass in enumerate(masses): 

760 m2 = (ams - mass) ** 2 

761 symbolmap[self.types[i]] = chemical_symbols[m2.argmin()] 

762 typemap[self.types[i]] = newtype( 

763 chemical_symbols[m2.argmin()], types 

764 ) 

765 types.append(typemap[self.types[i]]) 

766 for atom in self: 

767 atom.symbol = symbolmap[atom.symbol] 

768 self.types = types 

769 

770 key = next_key() 

771 

772 def read_list(key_string, length, debug=False): 

773 if key != key_string: 

774 return [], key 

775 

776 lst = [] 

777 while len(lines): 

778 w = lines.pop(0).split() 

779 if len(w) > length: 

780 lst.append([(int(w[1 + c]) - 1) for c in range(length)]) 

781 else: 

782 return lst, next_key() 

783 return lst, None 

784 

785 bonds, key = read_list('Bonds', 3) 

786 angles, key = read_list('Angles', 4) 

787 dihedrals, key = read_list('Dihedrals', 5, True) 

788 

789 self.connectivities = { 

790 'bonds': bonds, 

791 'angles': angles, 

792 'dihedrals': dihedrals, 

793 } 

794 

795 if 'bonds' in header: 

796 assert len(bonds) == header['bonds'] 

797 self.connectivities['bond types'] = list( 

798 range(header['bond types']) 

799 ) 

800 if 'angles' in header: 

801 assert len(angles) == header['angles'] 

802 self.connectivities['angle types'] = list( 

803 range(header['angle types']) 

804 ) 

805 if 'dihedrals' in header: 

806 assert len(dihedrals) == header['dihedrals'] 

807 self.connectivities['dihedral types'] = list( 

808 range(header['dihedral types']) 

809 )