Coverage for ase/io/siesta_output.py: 97.76%

134 statements  

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

1import numpy as np 

2 

3from ase.units import Bohr, Ry 

4 

5 

6class OutputReader: 

7 def __init__(self, prefix, directory, bandpath=None): 

8 self.prefix = prefix 

9 self.directory = directory 

10 self.bandpath = bandpath 

11 

12 def read_results(self): 

13 results = {} 

14 results['n_grid_point'] = self.read_number_of_grid_points() 

15 results.update(self.read_energy()) 

16 results.update(self.read_forces_stress()) 

17 results.update(self.read_eigenvalues()) 

18 results.update(self.read_kpoints()) 

19 results['dipole'] = self.read_dipole() 

20 

21 if self.bandpath is not None and len(self.bandpath.kpts): 

22 results['bandstructure'] = self.read_bands(self.bandpath) 

23 

24 return results 

25 

26 def _prefixed(self, extension): 

27 return self.directory / f'{self.prefix}.{extension}' 

28 

29 def read_bands(self, bandpath): 

30 fname = self._prefixed('bands') 

31 with open(fname) as fd: 

32 kpts, energies, efermi = read_bands_file(fd) 

33 return resolve_band_structure(bandpath, kpts, energies, efermi) 

34 

35 def read_number_of_grid_points(self): 

36 """Read number of grid points from SIESTA's text-output file.""" 

37 

38 fname = self.directory / f'{self.prefix}.out' 

39 with open(fname) as fd: 

40 for line in fd: 

41 line = line.strip().lower() 

42 if line.startswith('initmesh: mesh ='): 

43 return [int(word) for word in line.split()[3:8:2]] 

44 

45 raise RuntimeError 

46 

47 def read_energy(self): 

48 """Read energy from SIESTA's text-output file.""" 

49 text = self._prefixed('out').read_text().lower() 

50 

51 assert 'final energy' in text 

52 lines = iter(text.split('\n')) 

53 

54 # Get the energy and free energy the last time it appears 

55 for line in lines: 

56 has_energy = line.startswith('siesta: etot =') 

57 if has_energy: 

58 energy = float(line.split()[-1]) 

59 line = next(lines) 

60 # XXX dangerous, this should test the string in question. 

61 free_energy = float(line.split()[-1]) 

62 

63 return {'energy': energy, 'free_energy': free_energy} 

64 

65 def read_forces_stress(self): 

66 """Read the forces and stress from the FORCE_STRESS file.""" 

67 fname = self.directory / 'FORCE_STRESS' 

68 with open(fname) as fd: 

69 lines = fd.readlines() 

70 

71 stress_lines = lines[1:4] 

72 stress = np.empty((3, 3)) 

73 for i in range(3): 

74 line = stress_lines[i].strip().split(' ') 

75 line = [s for s in line if len(s) > 0] 

76 stress[i] = [float(s) for s in line] 

77 

78 results = {} 

79 results['stress'] = np.array( 

80 [ 

81 stress[0, 0], 

82 stress[1, 1], 

83 stress[2, 2], 

84 stress[1, 2], 

85 stress[0, 2], 

86 stress[0, 1], 

87 ] 

88 ) 

89 

90 results['stress'] *= Ry / Bohr**3 

91 

92 start = 5 

93 results['forces'] = np.zeros((len(lines) - start, 3), float) 

94 for i in range(start, len(lines)): 

95 line = [s for s in lines[i].strip().split(' ') if len(s) > 0] 

96 results['forces'][i - start] = [float(s) for s in line[2:5]] 

97 

98 results['forces'] *= Ry / Bohr 

99 return results 

100 

101 def read_eigenvalues(self): 

102 """A robust procedure using the suggestion by Federico Marchesin""" 

103 

104 file_name = self._prefixed('EIG') 

105 try: 

106 with open(file_name) as fd: 

107 fermi_energy = float(fd.readline()) 

108 n, num_hamilton_dim, nkp = map(int, fd.readline().split()) 

109 _ee = np.split(np.array(fd.read().split()).astype(float), nkp) 

110 except OSError: 

111 return {} 

112 

113 n_spin = 1 if num_hamilton_dim > 2 else num_hamilton_dim 

114 ksn2e = np.delete(_ee, 0, 1).reshape([nkp, n_spin, n]) 

115 

116 eig_array = np.empty((n_spin, nkp, n)) 

117 eig_array[:] = np.inf 

118 

119 for k, sn2e in enumerate(ksn2e): 

120 for s, n2e in enumerate(sn2e): 

121 eig_array[s, k, :] = n2e 

122 

123 assert np.isfinite(eig_array).all() 

124 return {'eigenvalues': eig_array, 'fermi_energy': fermi_energy} 

125 

126 def read_kpoints(self): 

127 """Reader of the .KP files""" 

128 

129 fname = self._prefixed('KP') 

130 try: 

131 with open(fname) as fd: 

132 nkp = int(next(fd)) 

133 kpoints = np.empty((nkp, 3)) 

134 kweights = np.empty(nkp) 

135 

136 for i in range(nkp): 

137 line = next(fd) 

138 tokens = line.split() 

139 numbers = np.array(tokens[1:]).astype(float) 

140 kpoints[i] = numbers[:3] 

141 kweights[i] = numbers[3] 

142 except OSError: 

143 return {} 

144 

145 return {'kpoints': kpoints, 'kpoint_weights': kweights} 

146 

147 def read_dipole(self): 

148 """Read dipole moment.""" 

149 dipole = np.zeros([1, 3]) 

150 with open(self._prefixed('out')) as fd: 

151 for line in fd: 

152 if line.rfind('Electric dipole (Debye)') > -1: 

153 dipole = np.array([float(f) for f in line.split()[5:8]]) 

154 # debye to e*Ang 

155 return dipole * 0.2081943482534 

156 

157 

158def read_bands_file(fd): 

159 efermi = float(next(fd)) 

160 next(fd) # Appears to be max/min energy. Not important for us 

161 header = next(fd) # Array shape: nbands, nspins, nkpoints 

162 nbands, nspins, nkpts = np.array(header.split()).astype(int) 

163 

164 # three fields for kpt coords, then all the energies 

165 ntokens = nbands * nspins + 3 

166 

167 # Read energies for each kpoint: 

168 data = [] 

169 for _ in range(nkpts): 

170 line = next(fd) 

171 tokens = line.split() 

172 while len(tokens) < ntokens: 

173 # Multirow table. Keep adding lines until the table ends, 

174 # which should happen exactly when we have all the energies 

175 # for this kpoint. 

176 line = next(fd) 

177 tokens += line.split() 

178 assert len(tokens) == ntokens 

179 values = np.array(tokens).astype(float) 

180 data.append(values) 

181 

182 data = np.array(data) 

183 assert len(data) == nkpts 

184 kpts = data[:, :3] 

185 energies = data[:, 3:] 

186 energies = energies.reshape(nkpts, nspins, nbands) 

187 assert energies.shape == (nkpts, nspins, nbands) 

188 return kpts, energies, efermi 

189 

190 

191def resolve_band_structure(path, kpts, energies, efermi): 

192 """Convert input BandPath along with Siesta outputs into BS object.""" 

193 # Right now this function doesn't do much. 

194 # 

195 # Not sure how the output kpoints in the siesta.bands file are derived. 

196 # They appear to be related to the lattice parameter. 

197 # 

198 # We should verify that they are consistent with our input path, 

199 # but since their meaning is unclear, we can't quite do so. 

200 # 

201 # Also we should perhaps verify the cell. If we had the cell, we 

202 # could construct the bandpath from scratch (i.e., pure outputs). 

203 from ase.spectrum.band_structure import BandStructure 

204 

205 ksn2e = energies 

206 skn2e = np.swapaxes(ksn2e, 0, 1) 

207 bs = BandStructure(path, skn2e, reference=efermi) 

208 return bs