Coverage for ase/io/nwchem/nwreader.py: 65.44%

272 statements  

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

1import re 

2from collections import OrderedDict 

3 

4import numpy as np 

5 

6from ase import Atoms 

7from ase.calculators.singlepoint import ( 

8 SinglePointDFTCalculator, 

9 SinglePointKPoint, 

10) 

11from ase.units import Bohr, Hartree 

12 

13from .parser import _define_pattern 

14 

15# Note to the reader of this code: Here and below we use the function 

16# _define_pattern from parser.py in this same directory to compile 

17# regular expressions. These compiled expressions are stored along with 

18# an example string that the expression should match in a list that 

19# is used during tests (test/nwchem/nwchem_parser.py) to ensure that 

20# the regular expressions are still working correctly. 

21 

22# Matches the beginning of a GTO calculation 

23_gauss_block = _define_pattern( 

24 r'^[\s]+NWChem (?:SCF|DFT) Module\n$', 

25 ' NWChem SCF Module\n', 

26) 

27 

28 

29# Matches the beginning of a plane wave calculation 

30_pw_block = _define_pattern( 

31 r'^[\s]+\*[\s]+NWPW (?:PSPW|BAND|PAW|Band Structure) Calculation' 

32 r'[\s]+\*[\s]*\n$', 

33 ' * NWPW PSPW Calculation *\n', 

34) 

35 

36 

37# Top-level parser 

38def read_nwchem_out(fobj, index=-1): 

39 """Splits an NWChem output file into chunks corresponding to 

40 individual single point calculations.""" 

41 lines = fobj.readlines() 

42 

43 if index == slice(-1, None, None): 

44 for line in lines: 

45 if _gauss_block.match(line): 

46 return [parse_gto_chunk(''.join(lines))] 

47 if _pw_block.match(line): 

48 return [parse_pw_chunk(''.join(lines))] 

49 raise ValueError( 

50 'This does not appear to be a valid NWChem output file.' 

51 ) 

52 

53 # First, find each SCF block 

54 group = [] 

55 atomslist = [] 

56 header = True 

57 lastgroup = [] 

58 lastparser = None 

59 parser = None 

60 for line in lines: 

61 group.append(line) 

62 if _gauss_block.match(line): 

63 next_parser = parse_gto_chunk 

64 elif _pw_block.match(line): 

65 next_parser = parse_pw_chunk 

66 else: 

67 continue 

68 

69 if header: 

70 header = False 

71 else: 

72 atoms = parser(''.join(group)) 

73 if atoms is None and parser is lastparser: 

74 atoms = parser(''.join(lastgroup + group)) 

75 if atoms is not None: 

76 atomslist[-1] = atoms 

77 lastgroup += group 

78 else: 

79 atomslist.append(atoms) 

80 lastgroup = group 

81 lastparser = parser 

82 group = [] 

83 parser = next_parser 

84 if not header: 

85 atoms = parser(''.join(group)) 

86 if atoms is not None: 

87 atomslist.append(atoms) 

88 

89 return atomslist[index] 

90 

91 

92# Matches a geometry block and returns the geometry specification lines 

93_geom = _define_pattern( 

94 r'\n[ \t]+Geometry \"[ \t\S]+\" -> \"[ \t\S]*\"[ \t]*\n' 

95 r'^[ \t-]+\n' 

96 r'(?:^[ \t\S]*\n){3}' 

97 r'^[ \t]+No\.[ \t]+Tag[ \t]+Charge[ \t]+X[ \t]+Y[ \t]+Z\n' 

98 r'^[ \t-]+\n' 

99 r'((?:^(?:[ \t]+[\S]+){6}[ \t]*\n)+)', 

100 """\ 

101 

102 Geometry "geometry" -> "" 

103 ------------------------- 

104 

105 Output coordinates in angstroms (scale by 1.889725989 to convert to a.u.) 

106 

107 No. Tag Charge X Y Z 

108 ---- ---------------- ---------- -------------- -------------- -------------- 

109 1 C 6.0000 0.00000000 0.00000000 0.00000000 

110 2 H 1.0000 0.62911800 0.62911800 0.62911800 

111 3 H 1.0000 -0.62911800 -0.62911800 0.62911800 

112 4 H 1.0000 0.62911800 -0.62911800 -0.62911800 

113""", 

114 re.M, 

115) 

116 

117# Unit cell parser 

118_cell_block = _define_pattern( 

119 r'^[ \t]+Lattice Parameters[ \t]*\n' 

120 r'^(?:[ \t\S]*\n){4}' 

121 r'((?:^(?:[ \t]+[\S]+){5}\n){3})', 

122 """\ 

123 Lattice Parameters 

124 ------------------ 

125 

126 lattice vectors in angstroms (scale by 1.889725989 to convert to a.u.) 

127 

128 a1=< 4.000 0.000 0.000 > 

129 a2=< 0.000 5.526 0.000 > 

130 a3=< 0.000 0.000 4.596 > 

131 a= 4.000 b= 5.526 c= 4.596 

132 alpha= 90.000 beta= 90.000 gamma= 90.000 

133 omega= 101.6 

134""", 

135 re.M, 

136) 

137 

138 

139# Parses the geometry and returns the corresponding Atoms object 

140def _parse_geomblock(chunk): 

141 geomblocks = _geom.findall(chunk) 

142 if not geomblocks: 

143 return None 

144 geomblock = geomblocks[-1].strip().split('\n') 

145 natoms = len(geomblock) 

146 symbols = [] 

147 pos = np.zeros((natoms, 3)) 

148 for i, line in enumerate(geomblock): 

149 line = line.strip().split() 

150 symbols.append(line[1]) 

151 pos[i] = [float(x) for x in line[3:6]] 

152 

153 cellblocks = _cell_block.findall(chunk) 

154 if cellblocks: 

155 cellblock = cellblocks[-1].strip().split('\n') 

156 cell = np.zeros((3, 3)) 

157 for i, line in enumerate(cellblock): 

158 line = line.strip().split() 

159 cell[i] = [float(x) for x in line[1:4]] 

160 else: 

161 cell = None 

162 return Atoms(symbols, positions=pos, cell=cell) 

163 

164 

165# GTO-specific parser stuff 

166 

167# Matches gradient block from a GTO calculation 

168_gto_grad = _define_pattern( 

169 r'^[ \t]+[\S]+[ \t]+ENERGY GRADIENTS[ \t]*[\n]+' 

170 r'^[ \t]+atom[ \t]+coordinates[ \t]+gradient[ \t]*\n' 

171 r'^(?:[ \t]+x[ \t]+y[ \t]+z){2}[ \t]*\n' 

172 r'((?:^(?:[ \t]+[\S]+){8}\n)+)[ \t]*\n', 

173 """\ 

174 UHF ENERGY GRADIENTS 

175 

176 atom coordinates gradient 

177 x y z x y z 

178 1 C 0.293457 -0.293457 0.293457 -0.000083 0.000083 -0.000083 

179 2 H 1.125380 1.355351 1.125380 0.000086 0.000089 0.000086 

180 3 H -1.355351 -1.125380 1.125380 -0.000089 -0.000086 0.000086 

181 4 H 1.125380 -1.125380 -1.355351 0.000086 -0.000086 -0.000089 

182 

183""", 

184 re.M, 

185) 

186 

187# Energy parsers for a variety of different GTO calculations 

188_e_gto = OrderedDict() 

189_e_gto['tce'] = _define_pattern( 

190 r'^[\s]+[\S]+[\s]+total energy \/ hartree[\s]+' 

191 r'=[\s]+([\S]+)[\s]*\n', 

192 ' CCD total energy / hartree = -75.715332545665888\n', 

193 re.M, 

194) 

195_e_gto['ccsd'] = _define_pattern( 

196 r'^[\s]+Total CCSD energy:[\s]+([\S]+)[\s]*\n', 

197 ' Total CCSD energy: -75.716168566598569\n', 

198 re.M, 

199) 

200_e_gto['tddft'] = _define_pattern( 

201 r'^[\s]+Excited state energy =[\s]+([\S]+)[\s]*\n', 

202 ' Excited state energy = -75.130134499965\n', 

203 re.M, 

204) 

205_e_gto['mp2'] = _define_pattern( 

206 r'^[\s]+Total MP2 energy[\s]+([\S]+)[\s]*\n', 

207 ' Total MP2 energy -75.708800087578\n', 

208 re.M, 

209) 

210_e_gto['mf'] = _define_pattern( 

211 r'^[\s]+Total (?:DFT|SCF) energy =[\s]+([\S]+)[\s]*\n', 

212 ' Total SCF energy = -75.585555997789\n', 

213 re.M, 

214) 

215 

216 

217# GTO parser 

218def parse_gto_chunk(chunk): 

219 atoms = None 

220 forces = None 

221 energy = None 

222 dipole = None 

223 for theory, pattern in _e_gto.items(): 

224 matches = pattern.findall(chunk) 

225 if matches: 

226 energy = float(matches[-1].replace('D', 'E')) * Hartree 

227 break 

228 

229 gradblocks = _gto_grad.findall(chunk) 

230 if gradblocks: 

231 gradblock = gradblocks[-1].strip().split('\n') 

232 natoms = len(gradblock) 

233 symbols = [] 

234 pos = np.zeros((natoms, 3)) 

235 forces = np.zeros((natoms, 3)) 

236 for i, line in enumerate(gradblock): 

237 line = line.strip().split() 

238 symbols.append(line[1]) 

239 pos[i] = [float(x) for x in line[2:5]] 

240 forces[i] = [-float(x) for x in line[5:8]] 

241 pos *= Bohr 

242 forces *= Hartree / Bohr 

243 atoms = Atoms(symbols, positions=pos) 

244 

245 dipole, _quadrupole = _get_multipole(chunk) 

246 

247 kpts = _get_gto_kpts(chunk) 

248 

249 if atoms is None: 

250 atoms = _parse_geomblock(chunk) 

251 

252 if atoms is None: 

253 return None 

254 

255 # SinglePointDFTCalculator doesn't support quadrupole moment currently 

256 calc = SinglePointDFTCalculator( 

257 atoms=atoms, 

258 energy=energy, 

259 free_energy=energy, # XXX Is this right? 

260 forces=forces, 

261 dipole=dipole, 

262 # quadrupole=quadrupole, 

263 ) 

264 calc.kpts = kpts 

265 atoms.calc = calc 

266 return atoms 

267 

268 

269# Extracts dipole and quadrupole moment for a GTO calculation 

270# Note on the regex: Some, but not all, versions of NWChem 

271# insert extra spaces in the blank lines. Do not remove the \s* 

272# in between \n and \n 

273_multipole = _define_pattern( 

274 r'^[ \t]+Multipole analysis of the density[ \t\S]*\n' 

275 r'^[ \t-]+\n\s*\n^[ \t\S]+\n^[ \t-]+\n' 

276 r'((?:(?:(?:[ \t]+[\S]+){7,8}\n)|[ \t]*\n){12})', 

277 """\ 

278 Multipole analysis of the density 

279 --------------------------------- 

280 

281 L x y z total alpha beta nuclear 

282 - - - - ----- ----- ---- ------- 

283 0 0 0 0 -0.000000 -5.000000 -5.000000 10.000000 

284 

285 1 1 0 0 0.000000 0.000000 0.000000 0.000000 

286 1 0 1 0 -0.000001 -0.000017 -0.000017 0.000034 

287 1 0 0 1 -0.902084 -0.559881 -0.559881 0.217679 

288 

289 2 2 0 0 -5.142958 -2.571479 -2.571479 0.000000 

290 2 1 1 0 -0.000000 -0.000000 -0.000000 0.000000 

291 2 1 0 1 0.000000 0.000000 0.000000 0.000000 

292 2 0 2 0 -3.153324 -3.807308 -3.807308 4.461291 

293 2 0 1 1 0.000001 -0.000009 -0.000009 0.000020 

294 2 0 0 2 -4.384288 -3.296205 -3.296205 2.208122 

295""", 

296 re.M, 

297) 

298 

299 

300# Parses the dipole and quadrupole moment from a GTO calculation 

301def _get_multipole(chunk): 

302 matches = _multipole.findall(chunk) 

303 if not matches: 

304 return None, None 

305 # This pulls the 5th column out of the multipole moments block; 

306 # this column contains the actual moments. 

307 moments = [ 

308 float(x.split()[4]) 

309 for x in matches[-1].split('\n') 

310 if x and not x.isspace() 

311 ] 

312 dipole = np.array(moments[1:4]) * Bohr 

313 quadrupole = np.zeros(9) 

314 quadrupole[[0, 1, 2, 4, 5, 8]] = [moments[4:]] 

315 quadrupole[[3, 6, 7]] = quadrupole[[1, 2, 5]] 

316 return dipole, quadrupole.reshape((3, 3)) * Bohr**2 

317 

318 

319# MO eigenvalue and occupancy parser for GTO calculations 

320_eval_block = _define_pattern( 

321 r'^[ \t]+[\S]+ Final (?:Alpha |Beta )?Molecular Orbital Analysis[ \t]*' 

322 r'\n^[ \t-]+\n\n' 

323 r'(?:^[ \t]+Vector [ \t\S]+\n(?:^[ \t\S]+\n){3}' 

324 r'(?:^(?:(?:[ \t]+[\S]+){5}){1,2}[ \t]*\n)+\n)+', 

325 """\ 

326 ROHF Final Molecular Orbital Analysis 

327 ------------------------------------- 

328 

329 Vector 1 Occ=2.000000D+00 E=-2.043101D+01 

330 MO Center= 1.1D-20, 1.5D-18, 1.2D-01, r^2= 1.5D-02 

331 Bfn. Coefficient Atom+Function Bfn. Coefficient Atom+Function  

332 ----- ------------ --------------- ----- ------------ --------------- 

333 1 0.983233 1 O s  

334 

335 Vector 2 Occ=2.000000D+00 E=-1.324439D+00 

336 MO Center= -2.1D-18, -8.6D-17, -7.1D-02, r^2= 5.1D-01 

337 Bfn. Coefficient Atom+Function Bfn. Coefficient Atom+Function  

338 ----- ------------ --------------- ----- ------------ --------------- 

339 6 0.708998 1 O s 1 -0.229426 1 O s  

340 2 0.217752 1 O s  

341 """, # noqa: W291 

342 re.M, 

343) 

344 

345 

346# Parses the eigenvalues and occupations from a GTO calculation 

347def _get_gto_kpts(chunk): 

348 eval_blocks = _eval_block.findall(chunk) 

349 if not eval_blocks: 

350 return [] 

351 kpts = [] 

352 kpt = _get_gto_evals(eval_blocks[-1]) 

353 if kpt.s == 1: 

354 kpts.append(_get_gto_evals(eval_blocks[-2])) 

355 kpts.append(kpt) 

356 return kpts 

357 

358 

359# Extracts MO eigenvalue and occupancy for a GTO calculation 

360_extract_vector = _define_pattern( 

361 r'^[ \t]+Vector[ \t]+([\S])+[ \t]+Occ=([\S]+)[ \t]+E=[ \t]*([\S]+)[ \t]*\n', 

362 ' Vector 1 Occ=2.000000D+00 E=-2.043101D+01\n', 

363 re.M, 

364) 

365 

366 

367# Extracts the eigenvalues and occupations from a GTO calculation 

368def _get_gto_evals(chunk): 

369 spin = 1 if re.match(r'[ \t\S]+Beta', chunk) else 0 

370 data = [] 

371 for vector in _extract_vector.finditer(chunk): 

372 data.append([float(x.replace('D', 'E')) for x in vector.groups()[1:]]) 

373 data = np.array(data) 

374 occ = data[:, 0] 

375 energies = data[:, 1] * Hartree 

376 

377 return SinglePointKPoint(1.0, spin, 0, energies, occ) 

378 

379 

380# Plane wave specific parsing stuff 

381 

382# Matches the gradient block from a plane wave calculation 

383_nwpw_grad = _define_pattern( 

384 r'^[ \t]+[=]+[ \t]+Ion Gradients[ \t]+[=]+[ \t]*\n' 

385 r'^[ \t]+Ion Forces:[ \t]*\n' 

386 r'((?:^(?:[ \t]+[\S]+){7}\n)+)', 

387 """\ 

388 ============= Ion Gradients ================= 

389 Ion Forces: 

390 1 O ( -0.000012 0.000027 -0.005199 ) 

391 2 H ( 0.000047 -0.013082 0.020790 ) 

392 3 H ( 0.000047 0.012863 0.020786 ) 

393 C.O.M. ( -0.000000 -0.000000 -0.000000 ) 

394 =============================================== 

395""", 

396 re.M, 

397) 

398 

399# Matches the gradient block from a PAW calculation 

400_paw_grad = _define_pattern( 

401 r'^[ \t]+[=]+[ \t]+Ion Gradients[ \t]+[=]+[ \t]*\n' 

402 r'^[ \t]+Ion Positions:[ \t]*\n' 

403 r'((?:^(?:[ \t]+[\S]+){7}\n)+)' 

404 r'^[ \t]+Ion Forces:[ \t]*\n' 

405 r'((?:^(?:[ \t]+[\S]+){7}\n)+)', 

406 """\ 

407 ============= Ion Gradients ================= 

408 Ion Positions: 

409 1 O ( -3.77945 -5.22176 -3.77945 ) 

410 2 H ( -3.77945 -3.77945 3.77945 ) 

411 3 H ( -3.77945 3.77945 3.77945 ) 

412 Ion Forces: 

413 1 O ( -0.00001 -0.00000 0.00081 ) 

414 2 H ( 0.00005 -0.00026 -0.00322 ) 

415 3 H ( 0.00005 0.00030 -0.00322 ) 

416 C.O.M. ( -0.00000 -0.00000 -0.00000 ) 

417 =============================================== 

418""", 

419 re.M, 

420) 

421 

422# Energy parser for plane wave calculations 

423_nwpw_energy = _define_pattern( 

424 r'^[\s]+Total (?:PSPW|BAND|PAW) energy' 

425 r'[\s]+:[\s]+([\S]+)[\s]*\n', 

426 ' Total PSPW energy : -0.1709317826E+02\n', 

427 re.M, 

428) 

429 

430# Parser for the fermi energy in a plane wave calculation 

431_fermi_energy = _define_pattern( 

432 r'^[ \t]+Fermi energy =[ \t]+([\S]+) \([ \t]+[\S]+[ \t]*\n', 

433 ' Fermi energy = -0.5585062E-01 ( -1.520eV)\n', 

434 re.M, 

435) 

436 

437 

438# Plane wave parser 

439def parse_pw_chunk(chunk): 

440 atoms = _parse_geomblock(chunk) 

441 if atoms is None: 

442 return None 

443 

444 energy = None 

445 efermi = None 

446 forces = None 

447 stress = None 

448 

449 matches = _nwpw_energy.findall(chunk) 

450 if matches: 

451 energy = float(matches[-1].replace('D', 'E')) * Hartree 

452 

453 matches = _fermi_energy.findall(chunk) 

454 if matches: 

455 efermi = float(matches[-1].replace('D', 'E')) * Hartree 

456 

457 gradblocks = _nwpw_grad.findall(chunk) 

458 if not gradblocks: 

459 gradblocks = _paw_grad.findall(chunk) 

460 if gradblocks: 

461 gradblock = gradblocks[-1].strip().split('\n') 

462 natoms = len(gradblock) 

463 symbols = [] 

464 forces = np.zeros((natoms, 3)) 

465 for i, line in enumerate(gradblock): 

466 line = line.strip().split() 

467 symbols.append(line[1]) 

468 forces[i] = [float(x) for x in line[3:6]] 

469 forces *= Hartree / Bohr 

470 

471 if atoms.cell: 

472 stress = _get_stress(chunk, atoms.cell) 

473 

474 ibz_kpts, kpts = _get_pw_kpts(chunk) 

475 

476 # NWChem does not calculate an energy extrapolated to the 0K limit, 

477 # so right now, energy and free_energy will be the same. 

478 calc = SinglePointDFTCalculator( 

479 atoms=atoms, 

480 energy=energy, 

481 efermi=efermi, 

482 free_energy=energy, 

483 forces=forces, 

484 stress=stress, 

485 ibzkpts=ibz_kpts, 

486 ) 

487 calc.kpts = kpts 

488 atoms.calc = calc 

489 return atoms 

490 

491 

492# Extracts stress tensor from a plane wave calculation 

493_stress = _define_pattern( 

494 r'[ \t]+[=]+[ \t]+(?:total gradient|E all FD)[ \t]+[=]+[ \t]*\n' 

495 r'^[ \t]+S =((?:(?:[ \t]+[\S]+){5}\n){3})[ \t=]+\n', 

496 """\ 

497 ============= total gradient ============== 

498 S = ( -0.22668 0.27174 0.19134 ) 

499 ( 0.23150 -0.26760 0.23226 ) 

500 ( 0.19090 0.27206 -0.22700 ) 

501 =================================================== 

502""", 

503 re.M, 

504) 

505 

506 

507# Extract stress tensor from a plane wave calculation 

508def _get_stress(chunk, cell): 

509 stress_blocks = _stress.findall(chunk) 

510 if not stress_blocks: 

511 return None 

512 stress_block = stress_blocks[-1] 

513 stress = np.zeros((3, 3)) 

514 for i, row in enumerate(stress_block.strip().split('\n')): 

515 stress[i] = [float(x) for x in row.split()[1:4]] 

516 stress = (stress @ cell) * Hartree / Bohr / cell.volume 

517 stress = 0.5 * (stress + stress.T) 

518 # convert from 3x3 array to Voigt form 

519 return stress.ravel()[[0, 4, 8, 5, 2, 1]] 

520 

521 

522# MO/band eigenvalue and occupancy parser for plane wave calculations 

523_nwpw_eval_block = _define_pattern( 

524 r'(?:(?:^[ \t]+Brillouin zone point:[ \t]+[\S]+[ \t]*\n' 

525 r'(?:[ \t\S]*\n){3,4})?' 

526 r'^[ \t]+(?:virtual )?orbital energies:\n' 

527 r'(?:^(?:(?:[ \t]+[\S]+){3,4}){1,2}[ \t]*\n)+\n{,3})+', 

528 """\ 

529 Brillouin zone point: 1 

530 weight= 0.074074 

531 k =< 0.333 0.333 0.333> . <b1,b2,b3>  

532 =< 0.307 0.307 0.307> 

533 

534 orbital energies: 

535 0.3919370E+00 ( 10.665eV) occ=1.000 

536 0.3908827E+00 ( 10.637eV) occ=1.000 0.4155535E+00 ( 11.308eV) occ=1.000 

537 0.3607689E+00 ( 9.817eV) occ=1.000 0.3827820E+00 ( 10.416eV) occ=1.000 

538 0.3544000E+00 ( 9.644eV) occ=1.000 0.3782641E+00 ( 10.293eV) occ=1.000 

539 0.3531137E+00 ( 9.609eV) occ=1.000 0.3778819E+00 ( 10.283eV) occ=1.000 

540 0.2596367E+00 ( 7.065eV) occ=1.000 0.2820723E+00 ( 7.676eV) occ=1.000 

541 

542 Brillouin zone point: 2 

543 weight= 0.074074 

544 k =< -0.000 0.333 0.333> . <b1,b2,b3>  

545 =< 0.614 0.000 0.000> 

546 

547 orbital energies: 

548 0.3967132E+00 ( 10.795eV) occ=1.000 

549 0.3920006E+00 ( 10.667eV) occ=1.000 0.4197952E+00 ( 11.423eV) occ=1.000 

550 0.3912442E+00 ( 10.646eV) occ=1.000 0.4125086E+00 ( 11.225eV) occ=1.000 

551 0.3910472E+00 ( 10.641eV) occ=1.000 0.4124238E+00 ( 11.223eV) occ=1.000 

552 0.3153977E+00 ( 8.582eV) occ=1.000 0.3379797E+00 ( 9.197eV) occ=1.000 

553 0.2801606E+00 ( 7.624eV) occ=1.000 0.3052478E+00 ( 8.306eV) occ=1.000 

554""", # noqa: E501, W291 

555 re.M, 

556) 

557 

558# Parser for kpoint weights for a plane wave calculation 

559_kpt_weight = _define_pattern( 

560 r'^[ \t]+Brillouin zone point:[ \t]+([\S]+)[ \t]*\n' 

561 r'^[ \t]+weight=[ \t]+([\S]+)[ \t]*\n', 

562 """\ 

563 Brillouin zone point: 1 

564 weight= 0.074074  

565""", # noqa: W291 

566 re.M, 

567) 

568 

569 

570# Parse eigenvalues and occupancies from a plane wave calculation 

571def _get_pw_kpts(chunk): 

572 eval_blocks = [] 

573 for block in _nwpw_eval_block.findall(chunk): 

574 if 'pathlength' not in block: 

575 eval_blocks.append(block) 

576 if not eval_blocks: 

577 return [] 

578 if 'virtual' in eval_blocks[-1]: 

579 occ_block = eval_blocks[-2] 

580 virt_block = eval_blocks[-1] 

581 else: 

582 occ_block = eval_blocks[-1] 

583 virt_block = '' 

584 kpts = NWChemKpts() 

585 _extract_pw_kpts(occ_block, kpts, 1.0) 

586 _extract_pw_kpts(virt_block, kpts, 0.0) 

587 for match in _kpt_weight.finditer(occ_block): 

588 index, weight = match.groups() 

589 kpts.set_weight(index, float(weight)) 

590 return kpts.to_ibz_kpts(), kpts.to_singlepointkpts() 

591 

592 

593# Helper class for keeping track of kpoints and converting to 

594# SinglePointKPoint objects. 

595class NWChemKpts: 

596 def __init__(self): 

597 self.data = {} 

598 self.ibz_kpts = {} 

599 self.weights = {} 

600 

601 def add_ibz_kpt(self, index, raw_kpt): 

602 kpt = np.array([float(x.strip('>')) for x in raw_kpt.split()[1:4]]) 

603 self.ibz_kpts[index] = kpt 

604 

605 def add_eval(self, index, spin, energy, occ): 

606 if index not in self.data: 

607 self.data[index] = {} 

608 if spin not in self.data[index]: 

609 self.data[index][spin] = [] 

610 self.data[index][spin].append((energy, occ)) 

611 

612 def set_weight(self, index, weight): 

613 self.weights[index] = weight 

614 

615 def to_ibz_kpts(self): 

616 if not self.ibz_kpts: 

617 return np.array([[0.0, 0.0, 0.0]]) 

618 sorted_kpts = sorted(list(self.ibz_kpts.items()), key=lambda x: x[0]) 

619 return np.array(list(zip(*sorted_kpts))[1]) 

620 

621 def to_singlepointkpts(self): 

622 kpts = [] 

623 for i, (index, spins) in enumerate(self.data.items()): 

624 weight = self.weights[index] 

625 for spin, (_, data) in enumerate(spins.items()): 

626 energies, occs = np.array(sorted(data, key=lambda x: x[0])).T 

627 kpts.append(SinglePointKPoint(weight, spin, i, energies, occs)) 

628 return kpts 

629 

630 

631# Extracts MO/band data from a pattern matched by _nwpw_eval_block above 

632_kpt = _define_pattern( 

633 r'^[ \t]+Brillouin zone point:[ \t]+([\S]+)[ \t]*\n' 

634 r'^[ \t]+weight=[ \t]+([\S])+[ \t]*\n' 

635 r'^[ \t]+k[ \t]+([ \t\S]+)\n' 

636 r'(?:^[ \t\S]*\n){1,2}' 

637 r'^[ \t]+(?:virtual )?orbital energies:\n' 

638 r'((?:^(?:(?:[ \t]+[\S]+){3,4}){1,2}[ \t]*\n)+)', 

639 """\ 

640 Brillouin zone point: 1 

641 weight= 0.074074 

642 k =< 0.333 0.333 0.333> . <b1,b2,b3>  

643 =< 0.307 0.307 0.307> 

644 

645 orbital energies: 

646 0.3919370E+00 ( 10.665eV) occ=1.000 

647 0.3908827E+00 ( 10.637eV) occ=1.000 0.4155535E+00 ( 11.308eV) occ=1.000 

648 0.3607689E+00 ( 9.817eV) occ=1.000 0.3827820E+00 ( 10.416eV) occ=1.000 

649 0.3544000E+00 ( 9.644eV) occ=1.000 0.3782641E+00 ( 10.293eV) occ=1.000 

650 0.3531137E+00 ( 9.609eV) occ=1.000 0.3778819E+00 ( 10.283eV) occ=1.000 

651 0.2596367E+00 ( 7.065eV) occ=1.000 0.2820723E+00 ( 7.676eV) occ=1.000 

652""", # noqa: E501, W291 

653 re.M, 

654) 

655 

656 

657# Extracts kpoints from a plane wave calculation 

658def _extract_pw_kpts(chunk, kpts, default_occ): 

659 for match in _kpt.finditer(chunk): 

660 point, weight, raw_kpt, orbitals = match.groups() 

661 index = int(point) - 1 

662 for line in orbitals.split('\n'): 

663 tokens = line.strip().split() 

664 if not tokens: 

665 continue 

666 ntokens = len(tokens) 

667 a_e = float(tokens[0]) * Hartree 

668 if ntokens % 3 == 0: 

669 a_o = default_occ 

670 else: 

671 a_o = float(tokens[3].split('=')[1]) 

672 kpts.add_eval(index, 0, a_e, a_o) 

673 

674 if ntokens <= 4: 

675 continue 

676 if ntokens == 6: 

677 b_e = float(tokens[3]) * Hartree 

678 b_o = default_occ 

679 elif ntokens == 8: 

680 b_e = float(tokens[4]) * Hartree 

681 b_o = float(tokens[7].split('=')[1]) 

682 kpts.add_eval(index, 1, b_e, b_o) 

683 kpts.set_weight(index, float(weight)) 

684 kpts.add_ibz_kpt(index, raw_kpt)