Coverage for ase/io/xsf.py: 96.32%

190 statements  

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

1import numpy as np 

2 

3from ase.atoms import Atoms 

4from ase.calculators.singlepoint import SinglePointCalculator 

5from ase.data import atomic_numbers 

6from ase.units import Hartree 

7from ase.utils import reader, writer 

8 

9 

10@writer 

11def write_xsf(fileobj, images, data=None, origin=None, span_vectors=None): 

12 is_anim = len(images) > 1 

13 

14 if is_anim: 

15 fileobj.write('ANIMSTEPS %d\n' % len(images)) 

16 

17 numbers = images[0].get_atomic_numbers() 

18 

19 pbc = images[0].get_pbc() 

20 npbc = sum(pbc) 

21 if pbc[2]: 

22 fileobj.write('CRYSTAL\n') 

23 assert npbc == 3 

24 elif pbc[1]: 

25 fileobj.write('SLAB\n') 

26 assert npbc == 2 

27 elif pbc[0]: 

28 fileobj.write('POLYMER\n') 

29 assert npbc == 1 

30 else: 

31 # (Header written as part of image loop) 

32 assert npbc == 0 

33 

34 cell_variable = False 

35 for image in images[1:]: 

36 if np.abs(images[0].cell - image.cell).max() > 1e-14: 

37 cell_variable = True 

38 break 

39 

40 for n, atoms in enumerate(images): 

41 anim_token = ' %d' % (n + 1) if is_anim else '' 

42 if pbc.any(): 

43 write_cell = n == 0 or cell_variable 

44 if write_cell: 

45 if cell_variable: 

46 fileobj.write(f'PRIMVEC{anim_token}\n') 

47 else: 

48 fileobj.write('PRIMVEC\n') 

49 cell = atoms.get_cell() 

50 for i in range(3): 

51 fileobj.write(' %.14f %.14f %.14f\n' % tuple(cell[i])) 

52 

53 fileobj.write(f'PRIMCOORD{anim_token}\n') 

54 else: 

55 fileobj.write(f'ATOMS{anim_token}\n') 

56 

57 # Get the forces if it's not too expensive: 

58 calc = atoms.calc 

59 if calc is not None and ( 

60 hasattr(calc, 'calculation_required') 

61 and not calc.calculation_required(atoms, ['forces']) 

62 ): 

63 forces = atoms.get_forces() / Hartree 

64 else: 

65 forces = None 

66 

67 pos = atoms.get_positions() 

68 

69 if pbc.any(): 

70 fileobj.write(' %d 1\n' % len(pos)) 

71 for a in range(len(pos)): 

72 fileobj.write(' %2d' % numbers[a]) 

73 fileobj.write(' %20.14f %20.14f %20.14f' % tuple(pos[a])) 

74 if forces is None: 

75 fileobj.write('\n') 

76 else: 

77 fileobj.write(' %20.14f %20.14f %20.14f\n' % tuple(forces[a])) 

78 

79 if data is None: 

80 return 

81 

82 fileobj.write('BEGIN_BLOCK_DATAGRID_3D\n') 

83 fileobj.write(' data\n') 

84 fileobj.write(' BEGIN_DATAGRID_3Dgrid#1\n') 

85 

86 data = np.asarray(data) 

87 if data.dtype == complex: 

88 data = np.abs(data) 

89 

90 shape = data.shape 

91 fileobj.write(' %d %d %d\n' % shape) 

92 

93 cell = atoms.get_cell() 

94 if origin is None: 

95 origin = np.zeros(3) 

96 for i in range(3): 

97 if not pbc[i]: 

98 origin += cell[i] / shape[i] 

99 fileobj.write(' %f %f %f\n' % tuple(origin)) 

100 

101 for i in range(3): 

102 # XXXX is this not just supposed to be the cell? 

103 # What's with the strange division? 

104 # This disagrees with the output of Octopus. Investigate 

105 if span_vectors is None: 

106 fileobj.write( 

107 ' %f %f %f\n' % tuple(cell[i] * (shape[i] + 1) / shape[i]) 

108 ) 

109 else: 

110 fileobj.write(' %f %f %f\n' % tuple(span_vectors[i])) 

111 

112 for k in range(shape[2]): 

113 for j in range(shape[1]): 

114 fileobj.write(' ') 

115 fileobj.write(' '.join(['%f' % d for d in data[:, j, k]])) 

116 fileobj.write('\n') 

117 fileobj.write('\n') 

118 

119 fileobj.write(' END_DATAGRID_3D\n') 

120 fileobj.write('END_BLOCK_DATAGRID_3D\n') 

121 

122 

123@reader 

124def iread_xsf(fileobj, read_data=False): 

125 """Yield images and optionally data from xsf file. 

126 

127 Yields image1, image2, ..., imageN[, data, origin, 

128 span_vectors]. 

129 

130 Images are Atoms objects and data is a numpy array. 

131 

132 It also returns the origin of the simulation box 

133 as a numpy array and its spanning vectors as a 

134 list of numpy arrays, if data is returned. 

135 

136 Presently supports only a single 3D datagrid.""" 

137 

138 def _line_generator_func(): 

139 for line in fileobj: 

140 line = line.strip() 

141 if not line or line.startswith('#'): 

142 continue # Discard comments and empty lines 

143 yield line 

144 

145 _line_generator = _line_generator_func() 

146 

147 def readline(): 

148 return next(_line_generator) 

149 

150 line = readline() 

151 

152 if line.startswith('ANIMSTEPS'): 

153 nimages = int(line.split()[1]) 

154 line = readline() 

155 else: 

156 nimages = 1 

157 

158 if line == 'CRYSTAL': 

159 pbc = (True, True, True) 

160 elif line == 'SLAB': 

161 pbc = (True, True, False) 

162 elif line == 'POLYMER': 

163 pbc = (True, False, False) 

164 else: 

165 assert line.startswith('ATOMS'), line # can also be ATOMS 1 

166 pbc = (False, False, False) 

167 

168 cell = None 

169 for n in range(nimages): 

170 if any(pbc): 

171 line = readline() 

172 if line.startswith('PRIMCOORD'): 

173 assert cell is not None # cell read from previous image 

174 else: 

175 assert line.startswith('PRIMVEC') 

176 cell = [] 

177 for i in range(3): 

178 cell.append([float(x) for x in readline().split()]) 

179 

180 line = readline() 

181 if line.startswith('CONVVEC'): # ignored; 

182 for i in range(3): 

183 readline() 

184 line = readline() 

185 

186 assert line.startswith('PRIMCOORD') 

187 natoms = int(readline().split()[0]) 

188 lines = [readline() for _ in range(natoms)] 

189 else: 

190 assert line.startswith('ATOMS'), line 

191 line = readline() 

192 lines = [] 

193 while not (line.startswith('ATOMS') or line.startswith('BEGIN')): 

194 lines.append(line) 

195 try: 

196 line = readline() 

197 except StopIteration: 

198 break 

199 if line.startswith('BEGIN'): 

200 # We read "too far" and accidentally got the header 

201 # of the data section. This happens only when parsing 

202 # ATOMS blocks, because one cannot infer their length. 

203 # We will remember the line until later then. 

204 data_header_line = line 

205 

206 numbers = [] 

207 positions = [] 

208 for positionline in lines: 

209 tokens = positionline.split() 

210 symbol = tokens[0] 

211 if symbol.isdigit(): 

212 numbers.append(int(symbol)) 

213 else: 

214 numbers.append(atomic_numbers[symbol.capitalize()]) 

215 positions.append([float(x) for x in tokens[1:]]) 

216 

217 positions = np.array(positions) 

218 if len(positions[0]) == 3: 

219 forces = None 

220 else: 

221 forces = positions[:, 3:] * Hartree 

222 positions = positions[:, :3] 

223 

224 image = Atoms(numbers, positions, cell=cell, pbc=pbc) 

225 

226 if forces is not None: 

227 image.calc = SinglePointCalculator(image, forces=forces) 

228 yield image 

229 

230 if read_data: 

231 if any(pbc): 

232 line = readline() 

233 else: 

234 line = data_header_line 

235 assert line.startswith('BEGIN_BLOCK_DATAGRID_3D') 

236 readline() # name 

237 line = readline() 

238 assert line.startswith('BEGIN_DATAGRID_3D') 

239 

240 shape = [int(x) for x in readline().split()] 

241 assert len(shape) == 3 

242 origin = [float(x) for x in readline().split()] 

243 origin = np.array(origin) 

244 

245 span_vectors = [] 

246 for i in range(3): 

247 span_vector = [float(x) for x in readline().split()] 

248 span_vector = np.array(span_vector) 

249 span_vectors.append(span_vector) 

250 span_vectors = np.array(span_vectors) 

251 assert len(span_vectors) == len(shape) 

252 

253 npoints = np.prod(shape) 

254 

255 data = [] 

256 line = readline() # First line of data 

257 while not line.startswith('END_DATAGRID_3D'): 

258 data.extend([float(x) for x in line.split()]) 

259 line = readline() 

260 assert len(data) == npoints 

261 data = np.array(data, float).reshape(shape[::-1]).T 

262 # Note that data array is Fortran-ordered 

263 yield data, origin, span_vectors 

264 

265 

266def read_xsf(fileobj, index=-1, read_data=False): 

267 images = list(iread_xsf(fileobj, read_data=read_data)) 

268 if read_data: 

269 array, origin, span_vectors = images[-1] 

270 images = images[:-1] 

271 return array, origin, span_vectors, images[index] 

272 return images[index]