Coverage for ase/io/dlp4.py: 89.19%

148 statements  

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

1"""Read/Write DL_POLY_4 CONFIG files""" 

2 

3import itertools 

4import re 

5from collections.abc import Generator, Iterable 

6from typing import IO 

7 

8import numpy as np 

9 

10from ase.atoms import Atoms 

11from ase.calculators.singlepoint import SinglePointCalculator 

12from ase.data import chemical_symbols 

13from ase.units import _amu, _auf, _auv 

14from ase.utils import reader, writer 

15 

16__all__ = ['read_dlp4', 'write_dlp4'] 

17 

18# dlp4 labels will be registered in atoms.arrays[DLP4_LABELS_KEY] 

19DLP4_LABELS_KEY = 'dlp4_labels' 

20DLP4_DISP_KEY = 'dlp4_displacements' 

21DLP_F_SI = 1.0e-10 * _amu / (1.0e-12 * 1.0e-12) # Å*Da/ps^2 

22DLP_F_ASE = DLP_F_SI / _auf 

23DLP_V_SI = 1.0e-10 / 1.0e-12 # Å/ps 

24DLP_V_ASE = DLP_V_SI / _auv 

25 

26 

27def _get_frame_positions(fd: IO) -> tuple[int, int, int, list[int]]: 

28 """Get positions of frames in HISTORY file.""" 

29 init_pos = fd.tell() 

30 

31 fd.seek(0) 

32 

33 record_len = len(fd.readline()) # system name, and record size 

34 

35 items = fd.readline().strip().split() 

36 

37 if len(items) not in (3, 5): 

38 raise RuntimeError('Cannot determine version of HISTORY file format.') 

39 

40 levcfg, imcon, natoms = map(int, items[0:3]) 

41 

42 if len(items) == 3: # DLPoly classic 

43 # we have to iterate over the entire file 

44 pos = [fd.tell() for line in fd if 'timestep' in line] 

45 else: 

46 nframes = int(items[3]) 

47 pos = [ 

48 ((natoms * (levcfg + 2) + 4) * i + 3) * record_len 

49 for i in range(nframes) 

50 ] 

51 

52 fd.seek(init_pos) 

53 return levcfg, imcon, natoms, pos 

54 

55 

56@reader 

57def read_dlp_history( 

58 fd: IO, index: int | slice | None = None, symbols: list[str] | None = None 

59) -> list[Atoms]: 

60 """Read a HISTORY file. 

61 

62 Compatible with DLP4 and DLP_CLASSIC. 

63 

64 *Index* can be integer or a slice. 

65 

66 Provide a list of element strings to symbols to ignore naming 

67 from the HISTORY file. 

68 """ 

69 return list(iread_dlp_history(fd, index, symbols)) 

70 

71 

72@reader 

73def iread_dlp_history( 

74 fd: IO, index: int | slice | None = None, symbols: list[str] | None = None 

75) -> Generator[Atoms, None, None]: 

76 """Generator version of read_dlp_history 

77 

78 Compatible with DLP4 and DLP_CLASSIC. 

79 

80 *Index* can be integer or a slice. 

81 

82 Provide a list of element strings to symbols to ignore naming 

83 from the HISTORY file. 

84 """ 

85 levcfg, imcon, natoms, pos = _get_frame_positions(fd) 

86 

87 positions: Iterable[int] = () 

88 if index is None: 

89 positions = pos 

90 elif isinstance(index, int): 

91 positions = (pos[index],) 

92 elif isinstance(index, slice): 

93 positions = itertools.islice(pos, index.start, index.stop, index.step) 

94 

95 for pos_i in positions: 

96 fd.seek(pos_i + 1) 

97 yield read_single_image( 

98 fd, levcfg, imcon, natoms, is_trajectory=True, symbols=symbols 

99 ) 

100 

101 

102@reader 

103def read_dlp4(fd: IO, symbols: list[str] | None = None) -> Atoms: 

104 """Read a DL_POLY_4 config/revcon file. 

105 

106 Typically used indirectly through read("filename", atoms, format="dlp4"). 

107 

108 Can be unforgiving with custom chemical element names. 

109 Please complain to alin@elena.space for bugs.""" 

110 

111 fd.readline() 

112 levcfg, imcon = map(int, fd.readline().split()[0:2]) 

113 

114 position = fd.tell() 

115 is_trajectory = fd.readline().split()[0] == 'timestep' 

116 

117 if not is_trajectory: 

118 # Difficult to distinguish between trajectory and non-trajectory 

119 # formats without reading one line too many. 

120 fd.seek(position) 

121 

122 natoms = int(fd.readline().split()[2]) if is_trajectory else None 

123 return read_single_image(fd, levcfg, imcon, natoms, is_trajectory, symbols) 

124 

125 

126def read_single_image( 

127 fd: IO, 

128 levcfg: int, 

129 imcon: int, 

130 natoms: int | None, 

131 is_trajectory: bool, 

132 symbols: list[str] | None = None, 

133) -> Atoms: 

134 """Read a DLP frame""" 

135 sym = symbols if symbols else [] 

136 positions = [] 

137 velocities = [] 

138 forces = [] 

139 charges = [] 

140 masses = [] 

141 disps: list[float | None] = [] 

142 labels = [] 

143 

144 is_pbc = imcon > 0 

145 

146 cell = np.zeros((3, 3), dtype=np.float64) 

147 if is_pbc or is_trajectory: 

148 for j, line in enumerate(itertools.islice(fd, 3)): 

149 cell[j, :] = np.array(line.split(), dtype=np.float64) 

150 

151 i = 0 

152 for i, line in enumerate(itertools.islice(fd, natoms), 1): 

153 match = re.match(r'\s*([A-Za-z][a-z]?)(\S*)', line) 

154 if not match: 

155 raise OSError(f'Line {line} does not match valid format.') 

156 

157 symbol, label = match.group(1, 2) 

158 symbol = symbol.capitalize() 

159 

160 if is_trajectory: 

161 mass, charge, *disp = map(float, line.split()[2:]) 

162 charges.append(charge) 

163 masses.append(mass) 

164 disps.extend(disp if disp else [None]) # type: ignore[list-item] 

165 

166 if not symbols: 

167 if symbol not in chemical_symbols: 

168 raise ValueError( 

169 f"Symbol '{symbol}' not found in chemical symbols table" 

170 ) 

171 sym.append(symbol) 

172 

173 # make sure label is not empty 

174 labels.append(label if label else '') 

175 

176 positions.append([float(x) for x in next(fd).split()[:3]]) 

177 if levcfg > 0: 

178 velocities.append( 

179 [float(x) * DLP_V_ASE for x in next(fd).split()[:3]] 

180 ) 

181 if levcfg > 1: 

182 forces.append([float(x) * DLP_F_ASE for x in next(fd).split()[:3]]) 

183 

184 if symbols and (i != len(symbols)): 

185 raise ValueError( 

186 f'Counter is at {i} but {len(symbols)} symbols provided.' 

187 ) 

188 

189 if imcon == 0: 

190 pbc = (False, False, False) 

191 elif imcon in (1, 2, 3): 

192 pbc = (True, True, True) 

193 elif imcon == 6: 

194 pbc = (True, True, False) 

195 elif imcon in (4, 5): 

196 raise ValueError(f'Unsupported imcon: {imcon}') 

197 else: 

198 raise ValueError(f'Invalid imcon: {imcon}') 

199 

200 atoms = Atoms( 

201 positions=positions, 

202 symbols=sym, 

203 cell=cell, 

204 pbc=pbc, 

205 # Cell is centered around (0, 0, 0) in dlp4: 

206 celldisp=-cell.sum(axis=0) / 2, 

207 ) 

208 

209 if is_trajectory: 

210 atoms.set_masses(masses) 

211 atoms.set_array(DLP4_DISP_KEY, disps, float) 

212 atoms.set_initial_charges(charges) 

213 

214 atoms.set_array(DLP4_LABELS_KEY, labels, str) 

215 if levcfg > 0: 

216 atoms.set_velocities(velocities) 

217 if levcfg > 1: 

218 atoms.calc = SinglePointCalculator(atoms, forces=forces) 

219 

220 return atoms 

221 

222 

223@writer 

224def write_dlp4( 

225 fd: IO, 

226 atoms: Atoms, 

227 levcfg: int = 0, 

228 title: str = 'CONFIG generated by ASE', 

229): 

230 """Write a DL_POLY_4 config file. 

231 

232 Typically used indirectly through write("filename", atoms, format="dlp4"). 

233 

234 Can be unforgiven with custom chemical element names. 

235 Please complain to alin@elena.space in case of bugs""" 

236 

237 def float_format(flt): 

238 return format(flt, '20.10f') 

239 

240 natoms = len(atoms) 

241 

242 if tuple(atoms.pbc) == (False, False, False): 

243 imcon = 0 

244 elif tuple(atoms.pbc) == (True, True, True): 

245 imcon = 3 

246 elif tuple(atoms.pbc) == (True, True, False): 

247 imcon = 6 

248 else: 

249 raise ValueError( 

250 f'Unsupported pbc: {atoms.pbc}. ' 

251 'Supported pbc are 000, 110, and 111.' 

252 ) 

253 

254 print(f'{title:72s}', file=fd) 

255 print(f'{levcfg:10d}{imcon:10d} {natoms}', file=fd) 

256 

257 if imcon > 0: 

258 for row in atoms.get_cell(): 

259 print(''.join(map(float_format, row)), file=fd) 

260 

261 vels = atoms.get_velocities() / DLP_V_ASE if levcfg > 0 else None 

262 forces = atoms.get_forces() / DLP_F_ASE if levcfg > 1 else None 

263 

264 labels = atoms.arrays.get(DLP4_LABELS_KEY) 

265 

266 for i, atom in enumerate(atoms): 

267 sym = atom.symbol 

268 if labels is not None: 

269 sym += labels[i] 

270 

271 print(f'{sym:8s}{atom.index + 1:10d}', file=fd) 

272 

273 to_write = (atom.x, atom.y, atom.z) 

274 print(''.join(map(float_format, to_write)), file=fd) 

275 

276 if levcfg > 0: 

277 to_write = ( 

278 vels[atom.index, :] if vels is not None else (0.0, 0.0, 0.0) 

279 ) 

280 print(''.join(map(float_format, to_write)), file=fd) 

281 

282 if levcfg > 1: 

283 to_write = ( 

284 forces[atom.index, :] if forces is not None else (0.0, 0.0, 0.0) 

285 ) 

286 print(''.join(map(float_format, to_write)), file=fd)