Coverage for ase/io/elk.py: 86.36%

264 statements  

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

1import collections 

2import numbers 

3from pathlib import Path 

4 

5import numpy as np 

6 

7from ase import Atoms 

8from ase.units import Bohr, Hartree 

9from ase.utils import reader, writer 

10 

11 

12@reader 

13def read_elk(fd): 

14 """Import ELK atoms definition. 

15 

16 Reads unitcell, atom positions, magmoms from elk.in/GEOMETRY.OUT file. 

17 """ 

18 

19 lines = fd.readlines() 

20 

21 scale = np.ones(4) # unit cell scale 

22 positions = [] 

23 cell = [] 

24 symbols = [] 

25 magmoms = [] 

26 

27 # find cell scale 

28 for n, line in enumerate(lines): 

29 if line.split() == []: 

30 continue 

31 if line.strip() == 'scale': 

32 scale[0] = float(lines[n + 1]) 

33 elif line.startswith('scale'): 

34 scale[int(line.strip()[-1])] = float(lines[n + 1]) 

35 for n, line in enumerate(lines): 

36 if line.split() == []: 

37 continue 

38 if line.startswith('avec'): 

39 cell = np.array( 

40 [ 

41 [float(v) * scale[1] for v in lines[n + 1].split()], 

42 [float(v) * scale[2] for v in lines[n + 2].split()], 

43 [float(v) * scale[3] for v in lines[n + 3].split()], 

44 ] 

45 ) 

46 if line.startswith('atoms'): 

47 lines1 = lines[n + 1 :] # start subsearch 

48 spfname = [] 

49 natoms = [] 

50 atpos = [] 

51 bfcmt = [] 

52 for n1, line1 in enumerate(lines1): 

53 if line1.split() == []: 

54 continue 

55 if 'spfname' in line1: 

56 spfnamenow = lines1[n1].split()[0] 

57 spfname.append(spfnamenow) 

58 natomsnow = int(lines1[n1 + 1].split()[0]) 

59 natoms.append(natomsnow) 

60 atposnow = [] 

61 bfcmtnow = [] 

62 for line in lines1[n1 + 2 : n1 + 2 + natomsnow]: 

63 atposnow.append([float(v) for v in line.split()[0:3]]) 

64 if len(line.split()) == 6: # bfcmt present 

65 bfcmtnow.append( 

66 [float(v) for v in line.split()[3:]] 

67 ) 

68 atpos.append(atposnow) 

69 bfcmt.append(bfcmtnow) 

70 # symbols, positions, magmoms based on ELK spfname, atpos, and bfcmt 

71 symbols = '' 

72 positions = [] 

73 magmoms = [] 

74 for n, s in enumerate(spfname): 

75 symbols += str(s[1:].split('.')[0]) * natoms[n] 

76 positions += atpos[n] # assumes fractional coordinates 

77 if len(bfcmt[n]) > 0: 

78 # how to handle cases of magmoms being one or three dim array? 

79 magmoms += [m[-1] for m in bfcmt[n]] 

80 atoms = Atoms(symbols, scaled_positions=positions, cell=[1, 1, 1]) 

81 if len(magmoms) > 0: 

82 atoms.set_initial_magnetic_moments(magmoms) 

83 # final cell scale 

84 cell = cell * scale[0] * Bohr 

85 

86 atoms.set_cell(cell, scale_atoms=True) 

87 atoms.pbc = True 

88 return atoms 

89 

90 

91@writer 

92def write_elk_in(fd, atoms, parameters=None): 

93 """ 

94 Writes an ASE Atoms object and optional parameters to an `elk.in` file. 

95 

96 The format of `elk.in` and the meaning of the parameters is documented under 

97 https://elk.sourceforge.io/. All numeric parameters that are passed using 

98 Elk-native keys must be in Elk units. 

99 

100 Parameters 

101 ---------- 

102 fd : file, str or pathlib.Path 

103 A file path or an opened, writable file or file-like object 

104 atoms : Atoms object 

105 An ASE Atoms object with the atomic structure 

106 parameters : dict 

107 The keys of the dict are the names of the input blocks. The dict values 

108 contain the contents of the input blocks. The contents can be several 

109 different types or data structures: 1) bool, str, int, float for scalar 

110 parameters; 2) iterables for input blocks containing several lines, 

111 one element per line; 3) iterables for several parameters in a line, 

112 where arrays are treated as iterables; 4) iterables at the innermost 

113 level describing array parameters 

114 

115 Raises 

116 ------ 

117 RuntimeError 

118 This exception is raised in case of inconsistencies between parameters. 

119 TypeError 

120 This exception is raised in case of a wrong parameter type. 

121 

122 Returns 

123 ------- 

124 None 

125 The function writes directly to the provided file object. 

126 

127 See Also 

128 -------- 

129 ase.calculators.elk.ELK : The ASE Elk calculator 

130 

131 Examples 

132 -------- 

133 >>> import numpy as np 

134 >>> from ase import Atoms 

135 >>> from ase.io.elk import write_elk_in 

136 >>> atoms = Atoms('FeAl', positions=[[0, 0, 0], [1.45]*3], cell=[2.9]*3) 

137 >>> params = {'tasks': [[0], [10]], 'ngridk': [8, 8, 8], 'nempty': 8, 

138 'bfieldc': np.array((0.0, 0.0, -0.01)), 'spinpol': True, 

139 'dft+u': ((2, 1), (1, 2, 0.183, 0.034911967))} 

140 >>> write_elk_in('/path/to/elk.in', atoms, parameters=params) 

141 Note: ``np.array((0.0, 0.0, -0.01))``, ``[0.0, 0.0, -0.01]``, 

142 ``[[0.0, 0.0, -0.01]]``, and any combinations of lists, tuples, and 

143 ndarrays, are equivalent 

144 """ 

145 

146 if parameters is None: 

147 parameters = {} 

148 

149 parameters = dict(parameters) 

150 

151 species_path = parameters.pop('species_dir', None) 

152 species_path = parameters.pop('sppath', species_path) 

153 

154 if parameters.get('spinpol') is None: 

155 if atoms.get_initial_magnetic_moments().any(): 

156 parameters['spinpol'] = True 

157 

158 if 'xctype' in parameters: 

159 if 'xc' in parameters: 

160 raise RuntimeError("You can't use both 'xctype' and 'xc'!") 

161 

162 if parameters.get('autokpt'): 

163 if 'kpts' in parameters: 

164 raise RuntimeError("You can't use both 'autokpt' and 'kpts'!") 

165 if 'ngridk' in parameters: 

166 raise RuntimeError("You can't use both 'autokpt' and 'ngridk'!") 

167 if 'ngridk' in parameters: 

168 if 'kpts' in parameters: 

169 raise RuntimeError("You can't use both 'ngridk' and 'kpts'!") 

170 

171 if parameters.get('autoswidth'): 

172 if 'smearing' in parameters: 

173 raise RuntimeError( 

174 "You can't use both 'autoswidth' and 'smearing'!" 

175 ) 

176 if 'swidth' in parameters: 

177 raise RuntimeError("You can't use both 'autoswidth' and 'swidth'!") 

178 

179 inp = {} 

180 inp.update(parameters) 

181 

182 if 'xc' in parameters: 

183 xctype = { 

184 'LDA': 3, # PW92 

185 'PBE': 20, 

186 'REVPBE': 21, 

187 'PBESOL': 22, 

188 'WC06': 26, 

189 'AM05': 30, 

190 'mBJLDA': (100, 208, 12), 

191 }[parameters['xc']] 

192 inp['xctype'] = xctype 

193 del inp['xc'] 

194 

195 if 'kpts' in parameters: 

196 # XXX should generalize kpts handling. 

197 from ase.calculators.calculator import kpts2mp 

198 

199 mp = kpts2mp(atoms, parameters['kpts']) 

200 inp['ngridk'] = tuple(mp) 

201 vkloff = [] # is this below correct? 

202 for nk in mp: 

203 if nk % 2 == 0: # shift kpoint away from gamma point 

204 vkloff.append(0.5) 

205 else: 

206 vkloff.append(0) 

207 inp['vkloff'] = vkloff 

208 del inp['kpts'] 

209 

210 if 'smearing' in parameters: 

211 name = parameters['smearing'][0].lower() 

212 if name == 'methfessel-paxton': 

213 stype = parameters['smearing'][2] 

214 else: 

215 stype = { 

216 'gaussian': 0, 

217 'fermi-dirac': 3, 

218 }[name] 

219 inp['stype'] = stype 

220 inp['swidth'] = parameters['smearing'][1] / Hartree 

221 del inp['smearing'] 

222 

223 # Elk seems to concatenate path and filename in such a way 

224 # that we must put a / at the end: 

225 if species_path is not None: 

226 inp['sppath'] = f"'{species_path.rstrip('/')}/'" 

227 

228 def get_string_value(value_): 

229 if isinstance(value_, bool): 

230 return f'.{("false", "true")[value_]}.' 

231 if isinstance(value_, (numbers.Real, str)): 

232 return f'{value_}' 

233 if isinstance(value_, collections.abc.Iterable): 

234 if all(isinstance(v, (str, numbers.Real)) for v in value_): 

235 return ' '.join(get_string_value(v) for v in value_) 

236 lines = [] 

237 for v in value_: 

238 if isinstance(v, (str, numbers.Real)): 

239 lines.append(get_string_value(v)) 

240 else: 

241 lines.append(' '.join(get_string_value(e) for e in v)) 

242 return '\n '.join(lines) 

243 raise TypeError(f'Field type cannot be {type(value_)}') 

244 

245 # write all keys 

246 for key, value in inp.items(): 

247 fd.write(f'{key}\n {get_string_value(value)}\n\n') 

248 

249 # cell 

250 fd.write('avec\n') 

251 for vec in atoms.cell: 

252 fd.write(' %.14f %.14f %.14f\n' % tuple(vec / Bohr)) 

253 fd.write('\n') 

254 

255 # atoms 

256 species = {} 

257 symbols = [] 

258 for a, (symbol, m) in enumerate( 

259 zip(atoms.get_chemical_symbols(), atoms.get_initial_magnetic_moments()) 

260 ): 

261 if symbol in species: 

262 species[symbol].append((a, m)) 

263 else: 

264 species[symbol] = [(a, m)] 

265 symbols.append(symbol) 

266 fd.write('atoms\n %d\n' % len(species)) 

267 # scaled = atoms.get_scaled_positions(wrap=False) 

268 scaled = np.linalg.solve(atoms.cell.T, atoms.positions.T).T 

269 for symbol in symbols: 

270 fd.write(f" '{symbol}.in' : spfname\n") 

271 fd.write(' %d\n' % len(species[symbol])) 

272 for a, m in species[symbol]: 

273 fd.write( 

274 ' %.14f %.14f %.14f 0.0 0.0 %.14f\n' 

275 % (tuple(scaled[a]) + (m,)) 

276 ) 

277 

278 

279class ElkReader: 

280 def __init__(self, path): 

281 self.path = Path(path) 

282 

283 def _read_everything(self): 

284 yield from self._read_energy() 

285 

286 with (self.path / 'INFO.OUT').open() as fd: 

287 yield from parse_elk_info(fd) 

288 

289 with (self.path / 'EIGVAL.OUT').open() as fd: 

290 yield from parse_elk_eigval(fd) 

291 

292 with (self.path / 'KPOINTS.OUT').open() as fd: 

293 yield from parse_elk_kpoints(fd) 

294 

295 def read_everything(self): 

296 dct = dict(self._read_everything()) 

297 

298 # The eigenvalue/occupation tables do not say whether there are 

299 # two spins, so we have to reshape them from 1 x K x SB to S x K x B: 

300 spinpol = dct.pop('spinpol') 

301 if spinpol: 

302 for name in 'eigenvalues', 'occupations': 

303 array = dct[name] 

304 _, nkpts, nbands_double = array.shape 

305 assert _ == 1 

306 assert nbands_double % 2 == 0 

307 nbands = nbands_double // 2 

308 newarray = np.empty((2, nkpts, nbands)) 

309 newarray[0, :, :] = array[0, :, :nbands] 

310 newarray[1, :, :] = array[0, :, nbands:] 

311 if name == 'eigenvalues': 

312 # Verify that eigenvalues are still sorted: 

313 diffs = np.diff(newarray, axis=2) 

314 assert all(diffs.flat[:] > 0) 

315 dct[name] = newarray 

316 return dct 

317 

318 def _read_energy(self): 

319 txt = (self.path / 'TOTENERGY.OUT').read_text() 

320 tokens = txt.split() 

321 energy = float(tokens[-1]) * Hartree 

322 yield 'free_energy', energy 

323 yield 'energy', energy 

324 

325 

326def parse_elk_kpoints(fd): 

327 header = next(fd) 

328 lhs, rhs = header.split(':', 1) 

329 assert 'k-point, vkl, wkpt' in rhs, header 

330 nkpts = int(lhs.strip()) 

331 

332 kpts = np.empty((nkpts, 3)) 

333 weights = np.empty(nkpts) 

334 

335 for ikpt in range(nkpts): 

336 line = next(fd) 

337 tokens = line.split() 

338 kpts[ikpt] = np.array(tokens[1:4]).astype(float) 

339 weights[ikpt] = float(tokens[4]) 

340 yield 'ibz_kpoints', kpts 

341 yield 'kpoint_weights', weights 

342 

343 

344def parse_elk_info(fd): 

345 dct = collections.defaultdict(list) 

346 fd = iter(fd) 

347 

348 spinpol = None 

349 converged = False 

350 actually_did_not_converge = False 

351 # Legacy code kept track of both these things, which is strange. 

352 # Why could a file both claim to converge *and* not converge? 

353 

354 # We loop over all lines and extract also data that occurs 

355 # multiple times (e.g. in multiple SCF steps) 

356 for line in fd: 

357 # "name of quantity : 1 2 3" 

358 tokens = line.split(':', 1) 

359 if len(tokens) == 2: 

360 lhs, rhs = tokens 

361 dct[lhs.strip()].append(rhs.strip()) 

362 

363 elif line.startswith('Convergence targets achieved'): 

364 converged = True 

365 elif 'reached self-consistent loops maximum' in line.lower(): 

366 actually_did_not_converge = True 

367 

368 if 'Spin treatment' in line: 

369 # (Somewhat brittle doing multi-line stuff here.) 

370 line = next(fd) 

371 spinpol = line.strip() == 'spin-polarised' 

372 

373 yield 'converged', converged and not actually_did_not_converge 

374 if spinpol is None: 

375 raise RuntimeError('Could not determine spin treatment') 

376 yield 'spinpol', spinpol 

377 

378 if 'Fermi' in dct: 

379 yield 'fermi_level', float(dct['Fermi'][-1]) * Hartree 

380 

381 if 'total force' in dct: 

382 forces = [] 

383 for line in dct['total force']: 

384 forces.append(line.split()) 

385 yield 'forces', np.array(forces, float) * (Hartree / Bohr) 

386 

387 

388def parse_elk_eigval(fd): 

389 

390 def match_int(line, word): 

391 number, colon, word1 = line.split() 

392 assert word1 == word 

393 assert colon == ':' 

394 return int(number) 

395 

396 def skip_spaces(line=''): 

397 while not line.strip(): 

398 line = next(fd) 

399 return line 

400 

401 line = skip_spaces() 

402 nkpts = match_int(line, 'nkpt') # 10 : nkpts 

403 line = next(fd) 

404 nbands = match_int(line, 'nstsv') # 15 : nstsv 

405 

406 eigenvalues = np.empty((nkpts, nbands)) 

407 occupations = np.empty((nkpts, nbands)) 

408 kpts = np.empty((nkpts, 3)) 

409 

410 for ikpt in range(nkpts): 

411 line = skip_spaces() 

412 tokens = line.split() 

413 assert tokens[-1] == 'vkl', tokens 

414 assert ikpt + 1 == int(tokens[0]) 

415 kpts[ikpt] = np.array(tokens[1:4]).astype(float) 

416 

417 line = next(fd) # "(state, eigenvalue and occupancy below)" 

418 assert line.strip().startswith('(state,'), line 

419 for iband in range(nbands): 

420 line = next(fd) 

421 tokens = line.split() # (band number, eigenval, occ) 

422 assert iband + 1 == int(tokens[0]) 

423 eigenvalues[ikpt, iband] = float(tokens[1]) 

424 occupations[ikpt, iband] = float(tokens[2]) 

425 

426 yield 'ibz_kpoints', kpts 

427 yield 'eigenvalues', eigenvalues[None] * Hartree 

428 yield 'occupations', occupations[None]