Coverage for ase/calculators/openmx/reader.py: 63.66%

465 statements  

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

1# flake8: noqa 

2""" 

3The ASE Calculator for OpenMX <https://www.openmx-square.org>: Python interface 

4to the software package for nano-scale material simulations based on density 

5functional theories. 

6 Copyright (C) 2018 JaeHwan Shim and JaeJun Yu 

7 

8 This program is free software: you can redistribute it and/or modify 

9 it under the terms of the GNU Lesser General Public License as published by 

10 the Free Software Foundation, either version 2.1 of the License, or 

11 (at your option) any later version. 

12 

13 This program is distributed in the hope that it will be useful, 

14 but WITHOUT ANY WARRANTY; without even the implied warranty of 

15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

16 GNU Lesser General Public License for more details. 

17 

18 You should have received a copy of the GNU Lesser General Public License 

19 along with ASE. If not, see <https://www.gnu.org/licenses/>. 

20""" 

21 

22# from ase.calculators import SinglePointDFTCalculator 

23import os 

24import struct 

25 

26import numpy as np 

27 

28from ase.io import ParseError 

29from ase.units import Bohr, Debye, Ha 

30 

31 

32def read_openmx(filename=None, debug=False): 

33 from ase import Atoms 

34 from ase.calculators.openmx import OpenMX 

35 

36 """ 

37 Read results from typical OpenMX output files and returns the atom object 

38 In default mode, it reads every implementd properties we could get from 

39 the files. Unlike previous version, we read the information based on file. 

40 previous results will be eraised unless previous results are written in the 

41 next calculation results. 

42 

43 Read the 'LABEL.log' file seems redundant. Because all the 

44 information should already be written in '.out' file. However, in the 

45 version 3.8.3, stress tensor are not written in the '.out' file. It only 

46 contained in the '.log' file. So... I implented reading '.log' file method 

47 """ 

48 log_data = read_file(get_file_name('.log', filename), debug=debug) 

49 restart_data = read_file(get_file_name('.dat#', filename), debug=debug) 

50 dat_data = read_file(get_file_name('.dat', filename), debug=debug) 

51 out_data = read_file(get_file_name('.out', filename), debug=debug) 

52 scfout_data = read_scfout_file(get_file_name('.scfout', filename)) 

53 band_data = read_band_file(get_file_name('.Band', filename)) 

54 # dos_data = read_dos_file(get_file_name('.Dos.val', filename)) 

55 """ 

56 First, we get every data we could get from the all results files. And then, 

57 reform the data to fit to data structure of Atom object. While doing this, 

58 Fix the unit to ASE format. 

59 """ 

60 parameters = get_parameters( 

61 out_data=out_data, 

62 log_data=log_data, 

63 restart_data=restart_data, 

64 dat_data=dat_data, 

65 scfout_data=scfout_data, 

66 band_data=band_data, 

67 ) 

68 atomic_formula = get_atomic_formula( 

69 out_data=out_data, 

70 log_data=log_data, 

71 restart_data=restart_data, 

72 scfout_data=scfout_data, 

73 dat_data=dat_data, 

74 ) 

75 results = get_results( 

76 out_data=out_data, 

77 log_data=log_data, 

78 restart_data=restart_data, 

79 scfout_data=scfout_data, 

80 dat_data=dat_data, 

81 band_data=band_data, 

82 ) 

83 

84 atoms = Atoms(**atomic_formula) 

85 

86 # XXX Creating OpenMX out of parameters directly is a security problem 

87 # since the data comes from files, and the files may contain 

88 # malicious content that would be interpreted as 'command' 

89 from ase.calculators.calculator import all_properties 

90 from ase.calculators.singlepoint import SinglePointDFTCalculator 

91 

92 common_properties = set(all_properties) & set(results) 

93 results = {key: results[key] for key in common_properties} 

94 

95 atoms.calc = SinglePointDFTCalculator(atoms, **results) 

96 

97 # atoms.calc = OpenMX(**parameters) 

98 # atoms.calc.results = results 

99 return atoms 

100 

101 

102def read_file(filename, debug=False): 

103 """ 

104 Read the 'LABEL.out' file. Using 'parameters.py', we read every 'allowed_ 

105 dat' dictionory. while reading a file, if one find the key matcheds That 

106 'patters', which indicates the property we want is written, it will returns 

107 the pair value of that key. For example, 

108 example will be written later 

109 """ 

110 from ase.calculators.openmx import parameters as param 

111 

112 if not os.path.isfile(filename): 

113 return {} 

114 param_keys = [ 

115 'integer_keys', 

116 'float_keys', 

117 'string_keys', 

118 'bool_keys', 

119 'list_int_keys', 

120 'list_float_keys', 

121 'list_bool_keys', 

122 'tuple_integer_keys', 

123 'tuple_float_keys', 

124 'tuple_float_keys', 

125 ] 

126 patterns = { 

127 'Stress tensor': ('stress', read_stress_tensor), 

128 'Dipole moment': ('dipole', read_dipole), 

129 'Fractional coordinates of': ( 

130 'scaled_positions', 

131 read_scaled_positions, 

132 ), 

133 'Utot.': ('energy', read_energy), 

134 'energies in': ('energies', read_energies), 

135 'Chemical Potential': ('chemical_potential', read_chemical_potential), 

136 '<coordinates.forces': ('forces', read_forces), 

137 'Eigenvalues (Hartree)': ('eigenvalues', read_eigenvalues), 

138 } 

139 special_patterns = { 

140 'Total spin moment': ( 

141 ('magmoms', 'total_magmom'), 

142 read_magmoms_and_total_magmom, 

143 ), 

144 } 

145 out_data = {} 

146 line = '\n' 

147 if debug: 

148 print(f'Read results from {filename}') 

149 with open(filename) as fd: 

150 """ 

151 Read output file line by line. When the `line` matches the pattern 

152 of certain keywords in `param.[dtype]_keys`, for example, 

153 

154 if line in param.string_keys: 

155 out_data[key] = read_string(line) 

156 

157 parse that line and store it to `out_data` in specified data type. 

158 To cover all `dtype` parameters, for loop was used, 

159 

160 for [dtype] in parameters_keys: 

161 if line in param.[dtype]_keys: 

162 out_data[key] = read_[dtype](line) 

163 

164 After found matched pattern, escape the for loop using `continue`. 

165 """ 

166 while line != '': 

167 pattern_matched = False 

168 line = fd.readline() 

169 try: 

170 _line = line.split()[0] 

171 except IndexError: 

172 continue 

173 for dtype_key in param_keys: 

174 dtype = dtype_key.rsplit('_', 1)[0] 

175 read_dtype = globals()['read_' + dtype] 

176 for key in param.__dict__[dtype_key]: 

177 if key in _line: 

178 out_data[get_standard_key(key)] = read_dtype(line) 

179 pattern_matched = True 

180 continue 

181 if pattern_matched: 

182 continue 

183 

184 for key in param.matrix_keys: 

185 if '<' + key in line: 

186 out_data[get_standard_key(key)] = read_matrix(line, key, fd) 

187 pattern_matched = True 

188 continue 

189 if pattern_matched: 

190 continue 

191 for key in patterns: 

192 if key in line: 

193 out_data[patterns[key][0]] = patterns[key][1]( 

194 line, fd, debug=debug 

195 ) 

196 pattern_matched = True 

197 continue 

198 if pattern_matched: 

199 continue 

200 for key in special_patterns: 

201 if key in line: 

202 a, b = special_patterns[key][1](line, fd) 

203 out_data[special_patterns[key][0][0]] = a 

204 out_data[special_patterns[key][0][1]] = b 

205 pattern_matched = True 

206 continue 

207 if pattern_matched: 

208 continue 

209 return out_data 

210 

211 

212def read_scfout_file(filename=None): 

213 """ 

214 Read the Developer output '.scfout' files. It Behaves like read_scfout.c, 

215 OpenMX module, but written in python. Note that some array are begin with 

216 1, not 0 

217 

218 atomnum: the number of total atoms 

219 Catomnum: the number of atoms in the central region 

220 Latomnum: the number of atoms in the left lead 

221 Ratomnum: the number of atoms in the left lead 

222 SpinP_switch: 

223 0: non-spin polarized 

224 1: spin polarized 

225 TCpyCell: the total number of periodic cells 

226 Solver: method for solving eigenvalue problem 

227 ChemP: chemical potential 

228 Valence_Electrons: total number of valence electrons 

229 Total_SpinS: total value of Spin (2*Total_SpinS = muB) 

230 E_Temp: electronic temperature 

231 Total_NumOrbs: the number of atomic orbitals in each atom 

232 size: Total_NumOrbs[atomnum+1] 

233 FNAN: the number of first neighboring atoms of each atom 

234 size: FNAN[atomnum+1] 

235 natn: global index of neighboring atoms of an atom ct_AN 

236 size: natn[atomnum+1][FNAN[ct_AN]+1] 

237 ncn: global index for cell of neighboring atoms of an atom ct_AN 

238 size: ncn[atomnum+1][FNAN[ct_AN]+1] 

239 atv: x,y,and z-components of translation vector of periodically copied cell 

240 size: atv[TCpyCell+1][4]: 

241 atv_ijk: i,j,and j number of periodically copied cells 

242 size: atv_ijk[TCpyCell+1][4]: 

243 tv[4][4]: unit cell vectors in Bohr 

244 rtv[4][4]: reciprocal unit cell vectors in Bohr^{-1} 

245 note: 

246 tv_i dot rtv_j = 2PI * Kronecker's delta_{ij} 

247 Gxyz[atomnum+1][60]: atomic coordinates in Bohr 

248 Hks: Kohn-Sham matrix elements of basis orbitals 

249 size: Hks[SpinP_switch+1] 

250 [atomnum+1] 

251 [FNAN[ct_AN]+1] 

252 [Total_NumOrbs[ct_AN]] 

253 [Total_NumOrbs[h_AN]] 

254 iHks: 

255 imaginary Kohn-Sham matrix elements of basis orbitals 

256 for alpha-alpha, beta-beta, and alpha-beta spin matrices 

257 of which contributions come from spin-orbit coupling 

258 and Hubbard U effective potential. 

259 size: iHks[3] 

260 [atomnum+1] 

261 [FNAN[ct_AN]+1] 

262 [Total_NumOrbs[ct_AN]] 

263 [Total_NumOrbs[h_AN]] 

264 OLP: overlap matrix 

265 size: OLP[atomnum+1] 

266 [FNAN[ct_AN]+1] 

267 [Total_NumOrbs[ct_AN]] 

268 [Total_NumOrbs[h_AN]] 

269 OLPpox: overlap matrix with position operator x 

270 size: OLPpox[atomnum+1] 

271 [FNAN[ct_AN]+1] 

272 [Total_NumOrbs[ct_AN]] 

273 [Total_NumOrbs[h_AN]] 

274 OLPpoy: overlap matrix with position operator y 

275 size: OLPpoy[atomnum+1] 

276 [FNAN[ct_AN]+1] 

277 [Total_NumOrbs[ct_AN]] 

278 [Total_NumOrbs[h_AN]] 

279 OLPpoz: overlap matrix with position operator z 

280 size: OLPpoz[atomnum+1] 

281 [FNAN[ct_AN]+1] 

282 [Total_NumOrbs[ct_AN]] 

283 [Total_NumOrbs[h_AN]] 

284 DM: overlap matrix 

285 size: DM[SpinP_switch+1] 

286 [atomnum+1] 

287 [FNAN[ct_AN]+1] 

288 [Total_NumOrbs[ct_AN]] 

289 [Total_NumOrbs[h_AN]] 

290 dipole_moment_core[4]: 

291 dipole_moment_background[4]: 

292 """ 

293 from numpy import cumsum as cum 

294 from numpy import insert as ins 

295 from numpy import split as spl 

296 from numpy import sum, zeros 

297 

298 if not os.path.isfile(filename): 

299 return {} 

300 

301 def easyReader(byte, data_type, shape): 

302 data_size = {'d': 8, 'i': 4} 

303 data_struct = {'d': float, 'i': int} 

304 dt = data_type 

305 ds = data_size[data_type] 

306 unpack = struct.unpack 

307 if len(byte) == ds: 

308 if dt == 'i': 

309 return data_struct[dt].from_bytes(byte, byteorder='little') 

310 elif dt == 'd': 

311 return np.array(unpack(dt * (len(byte) // ds), byte))[0] 

312 elif shape is not None: 

313 return np.array(unpack(dt * (len(byte) // ds), byte)).reshape(shape) 

314 else: 

315 return np.array(unpack(dt * (len(byte) // ds), byte)) 

316 

317 def inte(byte, shape=None): 

318 return easyReader(byte, 'i', shape) 

319 

320 def floa(byte, shape=None): 

321 return easyReader(byte, 'd', shape) 

322 

323 def readOverlap(atomnum, Total_NumOrbs, FNAN, natn, fd): 

324 myOLP = [] 

325 myOLP.append([]) 

326 for ct_AN in range(1, atomnum + 1): 

327 myOLP.append([]) 

328 TNO1 = Total_NumOrbs[ct_AN] 

329 for h_AN in range(FNAN[ct_AN] + 1): 

330 myOLP[ct_AN].append([]) 

331 Gh_AN = natn[ct_AN][h_AN] 

332 TNO2 = Total_NumOrbs[Gh_AN] 

333 for i in range(TNO1): 

334 myOLP[ct_AN][h_AN].append(floa(fd.read(8 * TNO2))) 

335 return myOLP 

336 

337 def readHam(SpinP_switch, FNAN, atomnum, Total_NumOrbs, natn, fd): 

338 Hks = [] 

339 for spin in range(SpinP_switch + 1): 

340 Hks.append([]) 

341 Hks[spin].append([np.zeros(FNAN[0] + 1)]) 

342 for ct_AN in range(1, atomnum + 1): 

343 Hks[spin].append([]) 

344 TNO1 = Total_NumOrbs[ct_AN] 

345 for h_AN in range(FNAN[ct_AN] + 1): 

346 Hks[spin][ct_AN].append([]) 

347 Gh_AN = natn[ct_AN][h_AN] 

348 TNO2 = Total_NumOrbs[Gh_AN] 

349 for i in range(TNO1): 

350 Hks[spin][ct_AN][h_AN].append(floa(fd.read(8 * TNO2))) 

351 return Hks 

352 

353 with open(filename, mode='rb') as fd: 

354 atomnum, SpinP_switch = inte(fd.read(8)) 

355 Catomnum, Latomnum, Ratomnum, TCpyCell = inte(fd.read(16)) 

356 atv = floa(fd.read(8 * 4 * (TCpyCell + 1)), shape=(TCpyCell + 1, 4)) 

357 atv_ijk = inte(fd.read(4 * 4 * (TCpyCell + 1)), shape=(TCpyCell + 1, 4)) 

358 Total_NumOrbs = np.insert(inte(fd.read(4 * (atomnum))), 0, 1, axis=0) 

359 FNAN = np.insert(inte(fd.read(4 * (atomnum))), 0, 0, axis=0) 

360 natn = ins( 

361 spl(inte(fd.read(4 * sum(FNAN[1:] + 1))), cum(FNAN[1:] + 1)), 

362 0, 

363 zeros(FNAN[0] + 1), 

364 axis=0, 

365 )[:-1] 

366 ncn = ins( 

367 spl(inte(fd.read(4 * np.sum(FNAN[1:] + 1))), cum(FNAN[1:] + 1)), 

368 0, 

369 np.zeros(FNAN[0] + 1), 

370 axis=0, 

371 )[:-1] 

372 tv = ins( 

373 floa(fd.read(8 * 3 * 4), shape=(3, 4)), 0, [0, 0, 0, 0], axis=0 

374 ) 

375 rtv = ins( 

376 floa(fd.read(8 * 3 * 4), shape=(3, 4)), 0, [0, 0, 0, 0], axis=0 

377 ) 

378 Gxyz = ins( 

379 floa(fd.read(8 * (atomnum) * 4), shape=(atomnum, 4)), 

380 0, 

381 [0.0, 0.0, 0.0, 0.0], 

382 axis=0, 

383 ) 

384 Hks = readHam(SpinP_switch, FNAN, atomnum, Total_NumOrbs, natn, fd) 

385 iHks = [] 

386 if SpinP_switch == 3: 

387 iHks = readHam(SpinP_switch, FNAN, atomnum, Total_NumOrbs, natn, fd) 

388 OLP = readOverlap(atomnum, Total_NumOrbs, FNAN, natn, fd) 

389 OLPpox = readOverlap(atomnum, Total_NumOrbs, FNAN, natn, fd) 

390 OLPpoy = readOverlap(atomnum, Total_NumOrbs, FNAN, natn, fd) 

391 OLPpoz = readOverlap(atomnum, Total_NumOrbs, FNAN, natn, fd) 

392 DM = readHam(SpinP_switch, FNAN, atomnum, Total_NumOrbs, natn, fd) 

393 Solver = inte(fd.read(4)) 

394 ChemP, E_Temp = floa(fd.read(8 * 2)) 

395 dipole_moment_core = floa(fd.read(8 * 3)) 

396 dipole_moment_background = floa(fd.read(8 * 3)) 

397 Valence_Electrons, Total_SpinS = floa(fd.read(8 * 2)) 

398 

399 scf_out = { 

400 'atomnum': atomnum, 

401 'SpinP_switch': SpinP_switch, 

402 'Catomnum': Catomnum, 

403 'Latomnum': Latomnum, 

404 'Hks': Hks, 

405 'Ratomnum': Ratomnum, 

406 'TCpyCell': TCpyCell, 

407 'atv': atv, 

408 'Total_NumOrbs': Total_NumOrbs, 

409 'FNAN': FNAN, 

410 'natn': natn, 

411 'ncn': ncn, 

412 'tv': tv, 

413 'rtv': rtv, 

414 'Gxyz': Gxyz, 

415 'OLP': OLP, 

416 'OLPpox': OLPpox, 

417 'OLPpoy': OLPpoy, 

418 'OLPpoz': OLPpoz, 

419 'Solver': Solver, 

420 'ChemP': ChemP, 

421 'E_Temp': E_Temp, 

422 'dipole_moment_core': dipole_moment_core, 

423 'iHks': iHks, 

424 'dipole_moment_background': dipole_moment_background, 

425 'Valence_Electrons': Valence_Electrons, 

426 'atv_ijk': atv_ijk, 

427 'Total_SpinS': Total_SpinS, 

428 'DM': DM, 

429 } 

430 return scf_out 

431 

432 

433def read_band_file(filename=None): 

434 band_data = {} 

435 if not os.path.isfile(filename): 

436 return {} 

437 band_kpath = [] 

438 eigen_bands = [] 

439 with open(filename) as fd: 

440 line = fd.readline().split() 

441 nkpts = 0 

442 nband = int(line[0]) 

443 nspin = int(line[1]) + 1 

444 band_data['nband'] = nband 

445 band_data['nspin'] = nspin 

446 line = fd.readline().split() 

447 band_data['band_kpath_unitcell'] = [line[:3], line[3:6], line[6:9]] 

448 line = fd.readline().split() 

449 band_data['band_nkpath'] = int(line[0]) 

450 for _ in range(band_data['band_nkpath']): 

451 line = fd.readline().split() 

452 band_kpath.append(line) 

453 nkpts += int(line[0]) 

454 band_data['nkpts'] = nkpts 

455 band_data['band_kpath'] = band_kpath 

456 kpts = np.zeros((nkpts, 3)) 

457 eigen_bands = np.zeros((nspin, nkpts, nband)) 

458 for i in range(nspin): 

459 for j in range(nkpts): 

460 line = fd.readline() 

461 kpts[j] = np.array(line.split(), dtype=float)[1:] 

462 line = fd.readline() 

463 eigen_bands[i, j] = np.array(line.split(), dtype=float)[:] 

464 band_data['eigenvalues'] = eigen_bands 

465 band_data['band_kpts'] = kpts 

466 return band_data 

467 

468 

469def read_electron_valency(filename='H_CA13'): 

470 array = [] 

471 with open(filename) as fd: 

472 array = fd.readlines() 

473 fd.close() 

474 required_line = '' 

475 for line in array: 

476 if 'valence.electron' in line: 

477 required_line = line 

478 return rn(required_line) 

479 

480 

481def rn(line='\n', n=1): 

482 """ 

483 Read n'th to last value. 

484 For example: 

485 ... 

486 scf.XcType LDA 

487 scf.Kgrid 4 4 4 

488 ... 

489 In Python, 

490 >>> str(rn(line, 1)) 

491 LDA 

492 >>> line = fd.readline() 

493 >>> int(rn(line, 3)) 

494 4 

495 """ 

496 return line.split()[-n] 

497 

498 

499def read_tuple_integer(line): 

500 return tuple(int(x) for x in line.split()[-3:]) 

501 

502 

503def read_tuple_float(line): 

504 return tuple(float(x) for x in line.split()[-3:]) 

505 

506 

507def read_integer(line): 

508 return int(rn(line)) 

509 

510 

511def read_float(line): 

512 return float(rn(line)) 

513 

514 

515def read_string(line): 

516 return str(rn(line)) 

517 

518 

519def read_bool(line): 

520 bool = str(rn(line)).lower() 

521 if bool == 'on': 

522 return True 

523 elif bool == 'off': 

524 return False 

525 else: 

526 return None 

527 

528 

529def read_list_int(line): 

530 return [int(x) for x in line.split()[1:]] 

531 

532 

533def read_list_float(line): 

534 return [float(x) for x in line.split()[1:]] 

535 

536 

537def read_list_bool(line): 

538 return [read_bool(x) for x in line.split()[1:]] 

539 

540 

541def read_matrix(line, key, fd): 

542 matrix = [] 

543 line = fd.readline() 

544 while key not in line: 

545 matrix.append(line.split()) 

546 line = fd.readline() 

547 return matrix 

548 

549 

550def read_stress_tensor(line, fd, debug=None): 

551 fd.readline() # passing empty line 

552 fd.readline() 

553 line = fd.readline() 

554 xx, xy, xz = read_tuple_float(line) 

555 line = fd.readline() 

556 yx, yy, yz = read_tuple_float(line) 

557 line = fd.readline() 

558 zx, zy, zz = read_tuple_float(line) 

559 stress = [xx, yy, zz, (zy + yz) / 2, (zx + xz) / 2, (yx + xy) / 2] 

560 return stress 

561 

562 

563def read_magmoms_and_total_magmom(line, fd, debug=None): 

564 total_magmom = read_float(line) 

565 fd.readline() # Skip empty lines 

566 fd.readline() 

567 line = fd.readline() 

568 magmoms = [] 

569 while not (line == '' or line.isspace()): 

570 magmoms.append(read_float(line)) 

571 line = fd.readline() 

572 return magmoms, total_magmom 

573 

574 

575def read_energy(line, fd, debug=None): 

576 # It has Hartree unit yet 

577 return read_float(line) 

578 

579 

580def read_energies(line, fd, debug=None): 

581 line = fd.readline() 

582 if '***' in line: 

583 point = 7 # Version 3.8 

584 else: 

585 point = 16 # Version 3.9 

586 for _ in range(point): 

587 fd.readline() 

588 line = fd.readline() 

589 energies = [] 

590 while not (line == '' or line.isspace()): 

591 energies.append(float(line.split()[2])) 

592 line = fd.readline() 

593 return energies 

594 

595 

596def read_eigenvalues(line, fd, debug=False): 

597 """ 

598 Read the Eigenvalues in the `.out` file and returns the eigenvalue 

599 First, it assumes system have two spins and start reading until it reaches 

600 the end('*****...'). 

601 

602 eigenvalues[spin][kpoint][nbands] 

603 

604 For symmetry reason, `.out` file prints the eigenvalues at the half of the 

605 K points. Thus, we have to fill up the rest of the half. 

606 However, if the calculation was conducted only on the gamma point, it will 

607 raise the 'gamma_flag' as true and it will returns the original samples. 

608 """ 

609 

610 def prind(*line, end='\n'): 

611 if debug: 

612 print(*line, end=end) 

613 

614 prind('Read eigenvalues output') 

615 current_line = fd.tell() 

616 fd.seek(0) # Seek for the kgrid information 

617 while line != '': 

618 line = fd.readline().lower() 

619 if 'scf.kgrid' in line: 

620 break 

621 fd.seek(current_line) # Retrun to the original position 

622 

623 kgrid = read_tuple_integer(line) 

624 

625 if kgrid != (): 

626 prind('Non-Gamma point calculation') 

627 prind('scf.Kgrid is %d, %d, %d' % kgrid) 

628 gamma_flag = False 

629 # fd.seek(f.tell()+57) 

630 else: 

631 prind('Gamma point calculation') 

632 gamma_flag = True 

633 line = fd.readline() 

634 line = fd.readline() 

635 

636 eigenvalues = [] 

637 eigenvalues.append([]) 

638 eigenvalues.append([]) # Assume two spins 

639 i = 0 

640 while True: 

641 # Go to eigenvalues line 

642 while line != '': 

643 line = fd.readline() 

644 prind(line) 

645 ll = line.split() 

646 if line.isspace(): 

647 continue 

648 elif len(ll) > 1: 

649 if ll[0] == '1': 

650 break 

651 elif '*****' in line: 

652 break 

653 

654 # Break if it reaches the end or next parameters 

655 if '*****' in line or line == '': 

656 break 

657 

658 # Check Number and format is valid 

659 try: 

660 # Suppose to be looks like 

661 # 1 -2.33424746491277 -2.33424746917880 

662 ll = line.split() 

663 # Check if it reaches the end of the file 

664 assert line != '' 

665 assert len(ll) == 3 

666 float(ll[1]) 

667 float(ll[2]) 

668 except (AssertionError, ValueError): 

669 raise ParseError('Cannot read eigenvalues') 

670 

671 # Read eigenvalues 

672 eigenvalues[0].append([]) 

673 eigenvalues[1].append([]) 

674 while not (line == '' or line.isspace()): 

675 eigenvalues[0][i].append(float(rn(line, 2))) 

676 eigenvalues[1][i].append(float(rn(line, 1))) 

677 line = fd.readline() 

678 prind(line, end='') 

679 i += 1 

680 prind(line) 

681 if gamma_flag: 

682 return np.asarray(eigenvalues) 

683 eigen_half = np.asarray(eigenvalues) 

684 prind(eigen_half) 

685 # Fill up the half 

686 spin, half_kpts, bands = eigen_half.shape 

687 even_odd = np.array(kgrid).prod() % 2 

688 eigen_values = np.zeros((spin, half_kpts * 2 - even_odd, bands)) 

689 for i in range(half_kpts): 

690 eigen_values[0, i] = eigen_half[0, i, :] 

691 eigen_values[1, i] = eigen_half[1, i, :] 

692 eigen_values[0, 2 * half_kpts - 1 - i - even_odd] = eigen_half[0, i, :] 

693 eigen_values[1, 2 * half_kpts - 1 - i - even_odd] = eigen_half[1, i, :] 

694 return eigen_values 

695 

696 

697def read_forces(line, fd, debug=None): 

698 # It has Hartree per Bohr unit yet 

699 forces = [] 

700 fd.readline() # Skip Empty line 

701 line = fd.readline() 

702 while 'coordinates.forces>' not in line: 

703 forces.append(read_tuple_float(line)) 

704 line = fd.readline() 

705 return np.array(forces) 

706 

707 

708def read_dipole(line, fd, debug=None): 

709 dipole = [] 

710 while 'Total' not in line: 

711 line = fd.readline() 

712 dipole.append(read_tuple_float(line)) 

713 return dipole 

714 

715 

716def read_scaled_positions(line, fd, debug=None): 

717 scaled_positions = [] 

718 fd.readline() # Skip Empty lines 

719 fd.readline() 

720 fd.readline() 

721 line = fd.readline() 

722 while not (line == '' or line.isspace()): # Detect empty line 

723 scaled_positions.append(read_tuple_float(line)) 

724 line = fd.readline() 

725 return scaled_positions 

726 

727 

728def read_chemical_potential(line, fd, debug=None): 

729 return read_float(line) 

730 

731 

732def get_parameters( 

733 out_data=None, 

734 log_data=None, 

735 restart_data=None, 

736 scfout_data=None, 

737 dat_data=None, 

738 band_data=None, 

739): 

740 """ 

741 From the given data sets, construct the dictionary 'parameters'. If data 

742 is in the paramerters, it will save it. 

743 """ 

744 from ase.calculators.openmx import parameters as param 

745 

746 scaned_data = [ 

747 dat_data, 

748 out_data, 

749 log_data, 

750 restart_data, 

751 scfout_data, 

752 band_data, 

753 ] 

754 openmx_keywords = [ 

755 param.tuple_integer_keys, 

756 param.tuple_float_keys, 

757 param.tuple_bool_keys, 

758 param.integer_keys, 

759 param.float_keys, 

760 param.string_keys, 

761 param.bool_keys, 

762 param.list_int_keys, 

763 param.list_bool_keys, 

764 param.list_float_keys, 

765 param.matrix_keys, 

766 ] 

767 parameters = {} 

768 for scaned_datum in scaned_data: 

769 for scaned_key in scaned_datum.keys(): 

770 for openmx_keyword in openmx_keywords: 

771 if scaned_key in get_standard_key(openmx_keyword): 

772 parameters[scaned_key] = scaned_datum[scaned_key] 

773 continue 

774 translated_parameters = get_standard_parameters(parameters) 

775 parameters.update(translated_parameters) 

776 return {k: v for k, v in parameters.items() if v is not None} 

777 

778 

779def get_standard_key(key): 

780 """ 

781 Standard ASE parameter format is to USE unerbar(_) instead of dot(.). Also, 

782 It is recommended to use lower case alphabet letter. Not Upper. Thus, we 

783 change the key to standard key 

784 For example: 

785 'scf.XcType' -> 'scf_xctype' 

786 """ 

787 if isinstance(key, str): 

788 return key.lower().replace('.', '_') 

789 elif isinstance(key, list): 

790 return [k.lower().replace('.', '_') for k in key] 

791 else: 

792 return [k.lower().replace('.', '_') for k in key] 

793 

794 

795def get_standard_parameters(parameters): 

796 """ 

797 Translate the OpenMX parameters to standard ASE parameters. For example, 

798 

799 scf.XcType -> xc 

800 scf.maxIter -> maxiter 

801 scf.energycutoff -> energy_cutoff 

802 scf.Kgrid -> kpts 

803 scf.EigenvalueSolver -> eigensolver 

804 scf.SpinPolarization -> spinpol 

805 scf.criterion -> convergence 

806 scf.Electric.Field -> external 

807 scf.Mixing.Type -> mixer 

808 scf.system.charge -> charge 

809 

810 We followed GPAW schem. 

811 """ 

812 from ase.calculators.openmx import parameters as param 

813 from ase.units import Bohr, Ha, Ry, fs, m, s 

814 

815 units = param.unit_dat_keywords 

816 standard_parameters = {} 

817 standard_units = { 

818 'eV': 1, 

819 'Ha': Ha, 

820 'Ry': Ry, 

821 'Bohr': Bohr, 

822 'fs': fs, 

823 'K': 1, 

824 'GV / m': 1e9 / 1.6e-19 / m, 

825 'Ha/Bohr': Ha / Bohr, 

826 'm/s': m / s, 

827 '_amu': 1, 

828 'Tesla': 1, 

829 } 

830 translated_parameters = { 

831 'scf.XcType': 'xc', 

832 'scf.maxIter': 'maxiter', 

833 'scf.energycutoff': 'energy_cutoff', 

834 'scf.Kgrid': 'kpts', 

835 'scf.EigenvalueSolver': 'eigensolver', 

836 'scf.SpinPolarization': 'spinpol', 

837 'scf.criterion': 'convergence', 

838 'scf.Electric.Field': 'external', 

839 'scf.Mixing.Type': 'mixer', 

840 'scf.system.charge': 'charge', 

841 } 

842 

843 for key in parameters.keys(): 

844 for openmx_key, standard_key in translated_parameters.items(): 

845 if key == get_standard_key(openmx_key): 

846 unit = standard_units.get(units.get(openmx_key), 1) 

847 standard_parameters[standard_key] = parameters[key] * unit 

848 standard_parameters['spinpol'] = parameters.get('scf_spinpolarization') 

849 return standard_parameters 

850 

851 

852def get_atomic_formula( 

853 out_data=None, 

854 log_data=None, 

855 restart_data=None, 

856 scfout_data=None, 

857 dat_data=None, 

858): 

859 """_formula'. 

860 OpenMX results gives following information. Since, we should pick one 

861 between position/scaled_position, scaled_positions are suppressed by 

862 default. We use input value of position. Not the position after 

863 calculation. It is temporal. 

864 

865 Atoms.SpeciesAndCoordinate -> symbols 

866 Atoms.SpeciesAndCoordinate -> positions 

867 Atoms.UnitVectors -> cell 

868 scaled_positions -> scaled_positions 

869 If `positions` and `scaled_positions` are both given, this key deleted 

870 magmoms -> magmoms, Single value for each atom or three numbers for each 

871 atom for non-collinear calculations. 

872 """ 

873 atomic_formula = {} 

874 parameters = { 

875 'symbols': list, 

876 'positions': list, 

877 'scaled_positions': list, 

878 'magmoms': list, 

879 'cell': list, 

880 } 

881 datas = [out_data, log_data, restart_data, scfout_data, dat_data] 

882 atoms_unitvectors = None 

883 atoms_spncrd_unit = 'ang' 

884 atoms_unitvectors_unit = 'ang' 

885 for data in datas: 

886 # positions unit save 

887 if 'atoms_speciesandcoordinates_unit' in data: 

888 atoms_spncrd_unit = data['atoms_speciesandcoordinates_unit'] 

889 # cell unit save 

890 if 'atoms_unitvectors_unit' in data: 

891 atoms_unitvectors_unit = data['atoms_unitvectors_unit'] 

892 # symbols, positions or scaled_positions 

893 if 'atoms_speciesandcoordinates' in data: 

894 atoms_spncrd = data['atoms_speciesandcoordinates'] 

895 # cell 

896 if 'atoms_unitvectors' in data: 

897 atoms_unitvectors = data['atoms_unitvectors'] 

898 # pbc 

899 if 'scf_eigenvaluesolver' in data: 

900 scf_eigenvaluesolver = data['scf_eigenvaluesolver'] 

901 # ??? 

902 for openmx_keyword in data.keys(): 

903 for standard_keyword in parameters: 

904 if openmx_keyword == standard_keyword: 

905 atomic_formula[standard_keyword] = data[openmx_keyword] 

906 

907 atomic_formula['symbols'] = [i[1] for i in atoms_spncrd] 

908 

909 openmx_spncrd_keyword = [[i[2], i[3], i[4]] for i in atoms_spncrd] 

910 # Positions 

911 positions_unit = atoms_spncrd_unit.lower() 

912 positions = np.array(openmx_spncrd_keyword, dtype=float) 

913 if positions_unit == 'ang': 

914 atomic_formula['positions'] = positions 

915 elif positions_unit == 'frac': 

916 scaled_positions = np.array(openmx_spncrd_keyword, dtype=float) 

917 atomic_formula['scaled_positions'] = scaled_positions 

918 elif positions_unit == 'au': 

919 positions = np.array(openmx_spncrd_keyword, dtype=float) * Bohr 

920 atomic_formula['positions'] = positions 

921 

922 # If Cluster, pbc is False, else it is True 

923 atomic_formula['pbc'] = scf_eigenvaluesolver.lower() != 'cluster' 

924 

925 # Cell Handling 

926 if atoms_unitvectors is not None: 

927 openmx_cell_keyword = atoms_unitvectors 

928 cell = np.array(openmx_cell_keyword, dtype=float) 

929 if atoms_unitvectors_unit.lower() == 'ang': 

930 atomic_formula['cell'] = openmx_cell_keyword 

931 elif atoms_unitvectors_unit.lower() == 'au': 

932 atomic_formula['cell'] = cell * Bohr 

933 

934 # If `positions` and `scaled_positions` are both given, delete `scaled_..` 

935 if ( 

936 atomic_formula.get('scaled_positions') is not None 

937 and atomic_formula.get('positions') is not None 

938 ): 

939 del atomic_formula['scaled_positions'] 

940 return atomic_formula 

941 

942 

943def get_results( 

944 out_data=None, 

945 log_data=None, 

946 restart_data=None, 

947 scfout_data=None, 

948 dat_data=None, 

949 band_data=None, 

950): 

951 """ 

952 From the gien data sets, construct the dictionary 'results' and return it' 

953 OpenMX version 3.8 can yield following properties 

954 free_energy, Ha # Same value with energy 

955 energy, Ha 

956 energies, Ha 

957 forces, Ha/Bohr 

958 stress(after 3.8 only) Ha/Bohr**3 

959 dipole Debye 

960 read_chemical_potential Ha 

961 magmoms muB ?? set to 1 

962 magmom muB ?? set to 1 

963 """ 

964 from numpy import array as arr 

965 

966 results = {} 

967 implemented_properties = { 

968 'free_energy': Ha, 

969 'energy': Ha, 

970 'energies': Ha, 

971 'forces': Ha / Bohr, 

972 'stress': Ha / Bohr**3, 

973 'dipole': Debye, 

974 'chemical_potential': Ha, 

975 'magmom': 1, 

976 'magmoms': 1, 

977 'eigenvalues': Ha, 

978 } 

979 data = [out_data, log_data, restart_data, scfout_data, dat_data, band_data] 

980 for datum in data: 

981 for key in datum.keys(): 

982 for property in implemented_properties: 

983 if key == property: 

984 results[key] = arr(datum[key]) * implemented_properties[key] 

985 return results 

986 

987 

988def get_file_name(extension='.out', filename=None, absolute_directory=True): 

989 directory, prefix = os.path.split(filename) 

990 if directory == '': 

991 directory = os.curdir 

992 if absolute_directory: 

993 return os.path.abspath(directory + '/' + prefix + extension) 

994 else: 

995 return os.path.basename(directory + '/' + prefix + extension)