Coverage for ase/calculators/turbomole/reader.py: 9.75%

564 statements  

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

1"""Functions to read from control file and from turbomole standard output""" 

2 

3import os 

4import re 

5import subprocess 

6import warnings 

7 

8import numpy as np 

9 

10from ase import Atom, Atoms 

11from ase.calculators.calculator import ReadError 

12from ase.units import Bohr, Ha 

13 

14 

15def execute_command(args): 

16 """execute commands like sdg, eiger""" 

17 proc = subprocess.Popen(args, stdout=subprocess.PIPE, encoding='ASCII') 

18 stdout, _stderr = proc.communicate() 

19 return stdout 

20 

21 

22def read_data_group(data_group): 

23 """read a turbomole data group from control file""" 

24 return execute_command(['sdg', data_group]).strip() 

25 

26 

27def parse_data_group(dgr, dg_name): 

28 """parse a data group""" 

29 if len(dgr) == 0: 

30 return None 

31 dg_key = '$' + dg_name 

32 if not dgr.startswith(dg_key): 

33 raise ValueError(f'data group does not start with {dg_key}') 

34 ndg = dgr.replace(dg_key, '').strip() 

35 ndg = re.sub(r'=\s+', '=', re.sub(r'\s+=', '=', ndg)) 

36 if all(c not in ndg for c in ('\n', ' ', '=')): 

37 return ndg 

38 lsep = '\n' if '\n' in dgr else ' ' 

39 result = {} 

40 lines = ndg.split(lsep) 

41 for line in lines: 

42 if len(line) == 0: 

43 continue 

44 ksep = '=' if '=' in line else None 

45 fields = line.strip().split(ksep) 

46 if len(fields) == 2: 

47 result[fields[0]] = fields[1] 

48 elif len(fields) == 1: 

49 result[fields[0]] = True 

50 return result 

51 

52 

53def read_output(regex, path): 

54 """collects all matching strings from the output""" 

55 hitlist = [] 

56 checkfiles = [] 

57 for filename in os.listdir(path): 

58 if filename.startswith('job.') or filename.endswith('.out'): 

59 checkfiles.append(filename) 

60 for filename in checkfiles: 

61 with open(filename) as f: 

62 lines = f.readlines() 

63 for line in lines: 

64 match = re.search(regex, line) 

65 if match: 

66 hitlist.append(match.group(1)) 

67 return hitlist 

68 

69 

70def read_version(path): 

71 """read the version from the tm output if stored in a file""" 

72 versions = read_output(r'TURBOMOLE\s+V(\d+\.\d+)\s+', path) 

73 if len(set(versions)) > 1: 

74 warnings.warn('different turbomole versions detected') 

75 version = list(set(versions)) 

76 elif len(versions) == 0: 

77 warnings.warn('no turbomole version detected') 

78 version = None 

79 else: 

80 version = versions[0] 

81 return version 

82 

83 

84def read_datetime(path): 

85 """read the datetime of the most recent calculation 

86 from the tm output if stored in a file 

87 """ 

88 datetimes = read_output( 

89 r'(\d{4}-[01]\d-[0-3]\d([T\s][0-2]\d:[0-5]' 

90 r'\d:[0-5]\d\.\d+)?([+-][0-2]\d:[0-5]\d|Z)?)', 

91 path, 

92 ) 

93 if len(datetimes) == 0: 

94 warnings.warn('no turbomole datetime detected') 

95 datetime = None 

96 else: 

97 # take the most recent time stamp 

98 datetime = sorted(datetimes, reverse=True)[0] 

99 return datetime 

100 

101 

102def read_runtime(path): 

103 """read the total runtime of calculations""" 

104 hits = read_output(r'total wall-time\s+:\s+(\d+.\d+)\s+seconds', path) 

105 if len(hits) == 0: 

106 warnings.warn('no turbomole runtimes detected') 

107 runtime = None 

108 else: 

109 runtime = np.sum([float(a) for a in hits]) 

110 return runtime 

111 

112 

113def read_hostname(path): 

114 """read the hostname of the computer on which the calc has run""" 

115 hostnames = read_output(r'hostname is\s+(.+)', path) 

116 if len(set(hostnames)) > 1: 

117 warnings.warn('runs on different hosts detected') 

118 hostname = list(set(hostnames)) 

119 else: 

120 hostname = hostnames[0] 

121 return hostname 

122 

123 

124def read_convergence(restart, parameters): 

125 """perform convergence checks""" 

126 if restart: 

127 if bool(len(read_data_group('restart'))): 

128 return False 

129 if bool(len(read_data_group('actual'))): 

130 return False 

131 if not bool(len(read_data_group('energy'))): 

132 return False 

133 if os.path.exists('job.start') and os.path.exists('GEO_OPT_FAILED'): 

134 return False 

135 return True 

136 

137 if parameters['task'] in ['optimize', 'geometry optimization']: 

138 if os.path.exists('GEO_OPT_CONVERGED'): 

139 return True 

140 elif os.path.exists('GEO_OPT_FAILED'): 

141 # check whether a failed scf convergence is the reason 

142 checkfiles = [] 

143 for filename in os.listdir('.'): 

144 if filename.startswith('job.'): 

145 checkfiles.append(filename) 

146 for filename in checkfiles: 

147 for line in open(filename): 

148 if 'SCF FAILED TO CONVERGE' in line: 

149 # scf did not converge in some jobex iteration 

150 if filename == 'job.last': 

151 raise RuntimeError('scf failed to converge') 

152 else: 

153 warnings.warn('scf failed to converge') 

154 warnings.warn('geometry optimization failed to converge') 

155 return False 

156 else: 

157 raise RuntimeError('error during geometry optimization') 

158 else: 

159 if os.path.isfile('dscf_problem'): 

160 raise RuntimeError('scf failed to converge') 

161 else: 

162 return True 

163 

164 

165def read_run_parameters(results): 

166 """read parameters set by define and not in self.parameters""" 

167 

168 if 'calculation parameters' not in results.keys(): 

169 results['calculation parameters'] = {} 

170 parameters = results['calculation parameters'] 

171 dg = read_data_group('symmetry') 

172 parameters['point group'] = str(dg.split()[1]) 

173 parameters['uhf'] = '$uhf' in read_data_group('uhf') 

174 # Gaussian function type 

175 gt = read_data_group('pople') 

176 if gt == '': 

177 parameters['gaussian type'] = 'spherical harmonic' 

178 else: 

179 gt = gt.split()[1] 

180 if gt == 'AO': 

181 parameters['gaussian type'] = 'spherical harmonic' 

182 elif gt == 'CAO': 

183 parameters['gaussian type'] = 'cartesian' 

184 else: 

185 parameters['gaussian type'] = None 

186 

187 nvibro = read_data_group('nvibro') 

188 if nvibro: 

189 parameters['nuclear degrees of freedom'] = int(nvibro.split()[1]) 

190 

191 

192def read_energy(results, post_HF): 

193 """Read energy from Turbomole energy file.""" 

194 try: 

195 with open('energy') as enf: 

196 text = enf.read().lower() 

197 except OSError: 

198 raise ReadError('failed to read energy file') 

199 if text == '': 

200 raise ReadError('empty energy file') 

201 

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

203 

204 for line in lines: 

205 if line.startswith('$end'): 

206 break 

207 elif line.startswith('$'): 

208 pass 

209 else: 

210 energy_tmp = float(line.split()[1]) 

211 if post_HF: 

212 energy_tmp += float(line.split()[4]) 

213 # update energy units 

214 e_total = energy_tmp * Ha 

215 results['total energy'] = e_total 

216 

217 

218def read_occupation_numbers(results): 

219 """read occupation numbers with module 'eiger'""" 

220 if 'molecular orbitals' not in results.keys(): 

221 return 

222 mos = results['molecular orbitals'] 

223 lines = execute_command(['eiger', '--all', '--pview']).split('\n') 

224 for line in lines: 

225 regex = ( 

226 r'^\s+(\d+)\.\s([\sab])\s*(\d+)\s?(\w+)' 

227 r'\s+(\d*\.*\d*)\s+([-+]?\d+\.\d*)' 

228 ) 

229 match = re.search(regex, line) 

230 if match: 

231 orb_index = int(match.group(3)) 

232 if match.group(2) == 'a': 

233 spin = 'alpha' 

234 elif match.group(2) == 'b': 

235 spin = 'beta' 

236 else: 

237 spin = None 

238 ar_index = next( 

239 index 

240 for (index, molecular_orbital) in enumerate(mos) 

241 if ( 

242 molecular_orbital['index'] == orb_index 

243 and molecular_orbital['spin'] == spin 

244 ) 

245 ) 

246 mos[ar_index]['index by energy'] = int(match.group(1)) 

247 irrep = str(match.group(4)) 

248 mos[ar_index]['irreducible representation'] = irrep 

249 if match.group(5) != '': 

250 mos[ar_index]['occupancy'] = float(match.group(5)) 

251 else: 

252 mos[ar_index]['occupancy'] = float(0) 

253 

254 

255def read_mos(results): 

256 """read the molecular orbital coefficients and orbital energies 

257 from files mos, alpha and beta""" 

258 

259 results['molecular orbitals'] = [] 

260 mos = results['molecular orbitals'] 

261 keywords = ['scfmo', 'uhfmo_alpha', 'uhfmo_beta'] 

262 spin = [None, 'alpha', 'beta'] 

263 converged = None 

264 

265 for index, keyword in enumerate(keywords): 

266 flen = None 

267 mo = {} 

268 orbitals_coefficients_line = [] 

269 mo_string = read_data_group(keyword) 

270 if mo_string == '': 

271 continue 

272 mo_string += '\n$end' 

273 lines = mo_string.split('\n') 

274 for line in lines: 

275 if re.match(r'^\s*#', line): 

276 continue 

277 if 'eigenvalue' in line: 

278 if len(orbitals_coefficients_line) != 0: 

279 mo['eigenvector'] = orbitals_coefficients_line 

280 mos.append(mo) 

281 mo = {} 

282 orbitals_coefficients_line = [] 

283 regex = ( 

284 r'^\s*(\d+)\s+(\S+)\s+' 

285 r'eigenvalue=([\+\-\d\.\w]+)\s' 

286 ) 

287 match = re.search(regex, line) 

288 mo['index'] = int(match.group(1)) 

289 mo['irreducible representation'] = str(match.group(2)) 

290 eig = float(re.sub('[dD]', 'E', match.group(3))) * Ha 

291 mo['eigenvalue'] = eig 

292 mo['spin'] = spin[index] 

293 mo['degeneracy'] = 1 

294 continue 

295 if keyword in line: 

296 # e.g. format(4d20.14) 

297 regex = r'format\(\d+[a-zA-Z](\d+)\.\d+\)' 

298 match = re.search(regex, line) 

299 if match: 

300 flen = int(match.group(1)) 

301 if ( 

302 'scfdump' in line 

303 or 'expanded' in line 

304 or 'scfconv' not in line 

305 ): 

306 converged = False 

307 continue 

308 if '$end' in line: 

309 if len(orbitals_coefficients_line) != 0: 

310 mo['eigenvector'] = orbitals_coefficients_line 

311 mos.append(mo) 

312 break 

313 sfields = [line[i : i + flen] for i in range(0, len(line), flen)] 

314 ffields = [ 

315 float(f.replace('D', 'E').replace('d', 'E')) for f in sfields 

316 ] 

317 orbitals_coefficients_line += ffields 

318 return converged 

319 

320 

321def read_basis_set(results): 

322 """read the basis set""" 

323 results['basis set'] = [] 

324 results['basis set formatted'] = {} 

325 bsf = read_data_group('basis') 

326 results['basis set formatted']['turbomole'] = bsf 

327 lines = bsf.split('\n') 

328 basis_set = {} 

329 functions = [] 

330 function = {} 

331 primitives = [] 

332 read_tag = False 

333 read_data = False 

334 for line in lines: 

335 if len(line.strip()) == 0: 

336 continue 

337 if '$basis' in line: 

338 continue 

339 if '$end' in line: 

340 break 

341 if re.match(r'^\s*#', line): 

342 continue 

343 if re.match(r'^\s*\*', line): 

344 if read_tag: 

345 read_tag = False 

346 read_data = True 

347 else: 

348 if read_data: 

349 # end primitives 

350 function['primitive functions'] = primitives 

351 function['number of primitives'] = len(primitives) 

352 primitives = [] 

353 functions.append(function) 

354 function = {} 

355 # end contracted 

356 basis_set['functions'] = functions 

357 functions = [] 

358 results['basis set'].append(basis_set) 

359 basis_set = {} 

360 read_data = False 

361 read_tag = True 

362 continue 

363 if read_tag: 

364 match = re.search(r'^\s*(\w+)\s+(.+)', line) 

365 if match: 

366 basis_set['element'] = match.group(1) 

367 basis_set['nickname'] = match.group(2) 

368 else: 

369 raise RuntimeError('error reading basis set') 

370 else: 

371 match = re.search(r'^\s+(\d+)\s+(\w+)', line) 

372 if match: 

373 if len(primitives) > 0: 

374 # end primitives 

375 function['primitive functions'] = primitives 

376 function['number of primitives'] = len(primitives) 

377 primitives = [] 

378 functions.append(function) 

379 function = {} 

380 # begin contracted 

381 function['shell type'] = str(match.group(2)) 

382 continue 

383 regex = ( 

384 r'^\s*([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)' 

385 r'\s+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)' 

386 ) 

387 match = re.search(regex, line) 

388 if match: 

389 exponent = float(match.group(1)) 

390 coefficient = float(match.group(3)) 

391 primitives.append( 

392 {'exponent': exponent, 'coefficient': coefficient} 

393 ) 

394 

395 

396def read_ecps(results): 

397 """read the effective core potentials""" 

398 ecpf = read_data_group('ecp') 

399 if not bool(len(ecpf)): 

400 results['ecps'] = None 

401 results['ecps formatted'] = None 

402 return 

403 results['ecps'] = [] 

404 results['ecps formatted'] = {} 

405 results['ecps formatted']['turbomole'] = ecpf 

406 lines = ecpf.split('\n') 

407 ecp = {} 

408 groups = [] 

409 group = {} 

410 terms = [] 

411 read_tag = False 

412 read_data = False 

413 for line in lines: 

414 if len(line.strip()) == 0: 

415 continue 

416 if '$ecp' in line: 

417 continue 

418 if '$end' in line: 

419 break 

420 if re.match(r'^\s*#', line): 

421 continue 

422 if re.match(r'^\s*\*', line): 

423 if read_tag: 

424 read_tag = False 

425 read_data = True 

426 else: 

427 if read_data: 

428 # end terms 

429 group['terms'] = terms 

430 group['number of terms'] = len(terms) 

431 terms = [] 

432 groups.append(group) 

433 group = {} 

434 # end group 

435 ecp['groups'] = groups 

436 groups = [] 

437 results['ecps'].append(ecp) 

438 ecp = {} 

439 read_data = False 

440 read_tag = True 

441 continue 

442 if read_tag: 

443 match = re.search(r'^\s*(\w+)\s+(.+)', line) 

444 if match: 

445 ecp['element'] = match.group(1) 

446 ecp['nickname'] = match.group(2) 

447 else: 

448 raise RuntimeError('error reading ecp') 

449 else: 

450 regex = r'ncore\s*=\s*(\d+)\s+lmax\s*=\s*(\d+)' 

451 match = re.search(regex, line) 

452 if match: 

453 ecp['number of core electrons'] = int(match.group(1)) 

454 ecp['maximum angular momentum number'] = int(match.group(2)) 

455 continue 

456 match = re.search(r'^(\w(\-\w)?)', line) 

457 if match: 

458 if len(terms) > 0: 

459 # end terms 

460 group['terms'] = terms 

461 group['number of terms'] = len(terms) 

462 terms = [] 

463 groups.append(group) 

464 group = {} 

465 # begin group 

466 group['title'] = str(match.group(1)) 

467 continue 

468 regex = ( 

469 r'^\s*([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)\s+' 

470 r'(\d)\s+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)' 

471 ) 

472 match = re.search(regex, line) 

473 if match: 

474 terms.append( 

475 { 

476 'coefficient': float(match.group(1)), 

477 'power of r': float(match.group(3)), 

478 'exponent': float(match.group(4)), 

479 } 

480 ) 

481 

482 

483def read_forces(results, natoms): 

484 """Read forces from Turbomole gradient file.""" 

485 dg = read_data_group('grad') 

486 if len(dg) == 0: 

487 return None 

488 with open('gradient') as file: 

489 lines = file.readlines() 

490 forces = np.array([[0, 0, 0]]) 

491 

492 nline = len(lines) 

493 iline = -1 

494 

495 for i in range(nline): 

496 if 'cycle' in lines[i]: 

497 iline = i 

498 

499 if iline < 0: 

500 raise RuntimeError('Please check TURBOMOLE gradients') 

501 

502 # next line 

503 iline += natoms + 1 

504 # $end line 

505 nline -= 1 

506 # read gradients 

507 for i in range(iline, nline): 

508 line = lines[i].replace('D', 'E') 

509 tmp = np.array([[float(f) for f in line.split()[0:3]]]) 

510 forces = np.concatenate((forces, tmp)) 

511 # Note the '-' sign for turbomole, to get forces 

512 forces = -np.delete(forces, np.s_[0:1], axis=0) * Ha / Bohr 

513 results['energy gradient'] = (-forces).tolist() 

514 return forces 

515 

516 

517def read_gradient(results): 

518 """read all information in file 'gradient'""" 

519 grad_string = read_data_group('grad') 

520 if len(grad_string) == 0: 

521 return 

522 # try to reuse ase: 

523 # structures = read('gradient', index=':') 

524 lines = grad_string.split('\n') 

525 history = [] 

526 image = {} 

527 gradient = [] 

528 atoms = Atoms() 

529 (cycle, energy, norm) = (None, None, None) 

530 for line in lines: 

531 # cycle lines 

532 regex = ( 

533 r'^\s*cycle =\s*(\d+)\s+' 

534 r'SCF energy =\s*([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)\s+' 

535 r'\|dE\/dxyz\| =\s*([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)' 

536 ) 

537 match = re.search(regex, line) 

538 if match: 

539 if len(atoms): 

540 image['optimization cycle'] = cycle 

541 image['total energy'] = energy 

542 image['gradient norm'] = norm 

543 image['energy gradient'] = gradient 

544 history.append(image) 

545 image = {} 

546 atoms = Atoms() 

547 gradient = [] 

548 cycle = int(match.group(1)) 

549 energy = float(match.group(2)) * Ha 

550 norm = float(match.group(4)) * Ha / Bohr 

551 continue 

552 # coordinate lines 

553 regex = ( 

554 r'^\s*([-+]?[0-9]*\.?[0-9]+([eEdD][-+]?[0-9]+)?)' 

555 r'\s+([-+]?[0-9]*\.?[0-9]+([eEdD][-+]?[0-9]+)?)' 

556 r'\s+([-+]?[0-9]*\.?[0-9]+([eEdD][-+]?[0-9]+)?)' 

557 r'\s+(\w+)' 

558 ) 

559 match = re.search(regex, line) 

560 if match: 

561 x = float(match.group(1)) * Bohr 

562 y = float(match.group(3)) * Bohr 

563 z = float(match.group(5)) * Bohr 

564 symbol = str(match.group(7)).capitalize() 

565 

566 if symbol == 'Q': 

567 symbol = 'X' 

568 atoms += Atom(symbol, (x, y, z)) 

569 

570 continue 

571 # gradient lines 

572 regex = ( 

573 r'^\s*([-+]?[0-9]*\.?[0-9]+([eEdD][-+]?[0-9]+)?)' 

574 r'\s+([-+]?[0-9]*\.?[0-9]+([eEdD][-+]?[0-9]+)?)' 

575 r'\s+([-+]?[0-9]*\.?[0-9]+([eEdD][-+]?[0-9]+)?)' 

576 ) 

577 match = re.search(regex, line) 

578 if match: 

579 gradx = float(match.group(1).replace('D', 'E')) * Ha / Bohr 

580 grady = float(match.group(3).replace('D', 'E')) * Ha / Bohr 

581 gradz = float(match.group(5).replace('D', 'E')) * Ha / Bohr 

582 gradient.append([gradx, grady, gradz]) 

583 

584 image['optimization cycle'] = cycle 

585 image['total energy'] = energy 

586 image['gradient norm'] = norm 

587 image['energy gradient'] = gradient 

588 history.append(image) 

589 results['geometry optimization history'] = history 

590 

591 

592def read_hessian(results, noproj=False): 

593 """Read in the hessian matrix""" 

594 results['hessian matrix'] = {} 

595 results['hessian matrix']['array'] = [] 

596 results['hessian matrix']['units'] = '?' 

597 results['hessian matrix']['projected'] = True 

598 results['hessian matrix']['mass weighted'] = True 

599 dg = read_data_group('nvibro') 

600 if len(dg) == 0: 

601 return 

602 nvibro = int(dg.split()[1]) 

603 results['hessian matrix']['dimension'] = nvibro 

604 row = [] 

605 key = 'hessian' 

606 if noproj: 

607 key = 'npr' + key 

608 results['hessian matrix']['projected'] = False 

609 lines = read_data_group(key).split('\n') 

610 for line in lines: 

611 if key in line: 

612 continue 

613 fields = line.split() 

614 row.extend(fields[2 : len(fields)]) 

615 if len(row) == nvibro: 

616 # check whether it is mass-weighted 

617 float_row = [float(element) for element in row] 

618 results['hessian matrix']['array'].append(float_row) 

619 row = [] 

620 

621 

622def read_normal_modes(results, noproj=False): 

623 """Read in vibrational normal modes""" 

624 results['normal modes'] = {} 

625 results['normal modes']['array'] = [] 

626 results['normal modes']['projected'] = True 

627 results['normal modes']['mass weighted'] = True 

628 results['normal modes']['units'] = '?' 

629 dg = read_data_group('nvibro') 

630 if len(dg) == 0: 

631 return 

632 nvibro = int(dg.split()[1]) 

633 results['normal modes']['dimension'] = nvibro 

634 row = [] 

635 key = 'vibrational normal modes' 

636 if noproj: 

637 key = 'npr' + key 

638 results['normal modes']['projected'] = False 

639 lines = read_data_group(key).split('\n') 

640 for line in lines: 

641 if key in line: 

642 continue 

643 if '$end' in line: 

644 break 

645 fields = line.split() 

646 row.extend(fields[2 : len(fields)]) 

647 if len(row) == nvibro: 

648 # check whether it is mass-weighted 

649 float_row = [float(element) for element in row] 

650 results['normal modes']['array'].append(float_row) 

651 row = [] 

652 

653 

654def read_vibrational_reduced_masses(results): 

655 """Read vibrational reduced masses""" 

656 results['vibrational reduced masses'] = [] 

657 dg = read_data_group('vibrational reduced masses') 

658 if len(dg) == 0: 

659 return 

660 lines = dg.split('\n') 

661 for line in lines: 

662 if '$vibrational' in line: 

663 continue 

664 if '$end' in line: 

665 break 

666 fields = [float(element) for element in line.split()] 

667 results['vibrational reduced masses'].extend(fields) 

668 

669 

670def read_vibrational_spectrum(results, noproj=False): 

671 """Read the vibrational spectrum""" 

672 results['vibrational spectrum'] = [] 

673 key = 'vibrational spectrum' 

674 if noproj: 

675 key = 'npr' + key 

676 lines = read_data_group(key).split('\n') 

677 for line in lines: 

678 dictionary = {} 

679 regex = ( 

680 r'^\s+(\d+)\s+(\S*)\s+([-+]?\d+\.\d*)' 

681 r'\s+(\d+\.\d*)\s+(\S+)\s+(\S+)' 

682 ) 

683 match = re.search(regex, line) 

684 if match: 

685 dictionary['mode number'] = int(match.group(1)) 

686 dictionary['irreducible representation'] = str(match.group(2)) 

687 dictionary['frequency'] = { 

688 'units': 'cm^-1', 

689 'value': float(match.group(3)), 

690 } 

691 dictionary['infrared intensity'] = { 

692 'units': 'km/mol', 

693 'value': float(match.group(4)), 

694 } 

695 

696 if match.group(5) == 'YES': 

697 dictionary['infrared active'] = True 

698 elif match.group(5) == 'NO': 

699 dictionary['infrared active'] = False 

700 else: 

701 dictionary['infrared active'] = None 

702 

703 if match.group(6) == 'YES': 

704 dictionary['Raman active'] = True 

705 elif match.group(6) == 'NO': 

706 dictionary['Raman active'] = False 

707 else: 

708 dictionary['Raman active'] = None 

709 

710 results['vibrational spectrum'].append(dictionary) 

711 

712 

713def read_ssquare(results): 

714 """Read the expectation value of S^2 operator""" 

715 s2_string = read_data_group('ssquare from dscf') 

716 if s2_string == '': 

717 return 

718 string = s2_string.split('\n')[1] 

719 ssquare = float(re.search(r'^\s*(\d+\.*\d*)', string).group(1)) 

720 results['ssquare from scf calculation'] = ssquare 

721 

722 

723def read_dipole_moment(results): 

724 """Read the dipole moment""" 

725 dip_string = read_data_group('dipole') 

726 if dip_string == '': 

727 return 

728 lines = dip_string.split('\n') 

729 for line in lines: 

730 regex = ( 

731 r'^\s+x\s+([-+]?\d+\.\d*)\s+y\s+([-+]?\d+\.\d*)' 

732 r'\s+z\s+([-+]?\d+\.\d*)\s+a\.u\.' 

733 ) 

734 match = re.search(regex, line) 

735 if match: 

736 dip_vec = [float(match.group(c)) for c in range(1, 4)] 

737 regex = r'^\s+\| dipole \| =\s+(\d+\.*\d*)\s+debye' 

738 match = re.search(regex, line) 

739 if match: 

740 dip_abs_val = float(match.group(1)) 

741 results['electric dipole moment'] = {} 

742 results['electric dipole moment']['vector'] = { 

743 'array': dip_vec, 

744 'units': 'a.u.', 

745 } 

746 results['electric dipole moment']['absolute value'] = { 

747 'value': dip_abs_val, 

748 'units': 'Debye', 

749 } 

750 

751 

752def read_charges(filename, natoms): 

753 """read partial charges on atoms from an ESP fit""" 

754 charges = None 

755 if os.path.exists(filename): 

756 with open(filename) as infile: 

757 lines = infile.readlines() 

758 oklines = None 

759 for n, line in enumerate(lines): 

760 if 'atom radius/au charge' in line: 

761 oklines = lines[n + 1 : n + natoms + 1] 

762 if oklines is not None: 

763 qm_charges = [float(line.split()[3]) for line in oklines] 

764 charges = np.array(qm_charges) 

765 return charges 

766 

767 

768def read_point_charges(): 

769 """read point charges from previous calculation""" 

770 pcs = read_data_group('point_charges') 

771 lines = pcs.split('\n')[1:] 

772 (charges, positions) = ([], []) 

773 for line in lines: 

774 columns = [float(col) for col in line.strip().split()] 

775 positions.append([col * Bohr for col in columns[0:3]]) 

776 charges.append(columns[3]) 

777 return charges, positions