Coverage for ase/io/gaussian.py: 95.17%

642 statements  

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

1import logging 

2import re 

3import warnings 

4from collections.abc import Iterable 

5from copy import deepcopy 

6 

7import numpy as np 

8 

9from ase import Atoms 

10from ase.calculators.calculator import Calculator, InputError 

11from ase.calculators.gaussian import Gaussian 

12from ase.calculators.singlepoint import SinglePointCalculator 

13from ase.data import atomic_masses_iupac2016, chemical_symbols 

14from ase.io import ParseError 

15from ase.io.zmatrix import parse_zmatrix 

16from ase.units import Bohr, Debye, Hartree 

17 

18logger = logging.getLogger(__name__) 

19 

20_link0_keys = [ 

21 'mem', 

22 'chk', 

23 'oldchk', 

24 'schk', 

25 'rwf', 

26 'oldmatrix', 

27 'oldrawmatrix', 

28 'int', 

29 'd2e', 

30 'save', 

31 'nosave', 

32 'errorsave', 

33 'cpu', 

34 'nprocshared', 

35 'gpucpu', 

36 'lindaworkers', 

37 'usessh', 

38 'ssh', 

39 'debuglinda', 

40] 

41 

42 

43_link0_special = [ 

44 'kjob', 

45 'subst', 

46] 

47 

48 

49# Certain problematic methods do not provide well-defined potential energy 

50# surfaces, because these "composite" methods involve geometry optimization 

51# and/or vibrational frequency analysis. In addition, the "energy" calculated 

52# by these methods are typically ZPVE corrected and/or temperature dependent 

53# free energies. 

54_problem_methods = [ 

55 'cbs-4m', 

56 'cbs-qb3', 

57 'cbs-apno', 

58 'g1', 

59 'g2', 

60 'g3', 

61 'g4', 

62 'g2mp2', 

63 'g3mp2', 

64 'g3b3', 

65 'g3mp2b3', 

66 'g4mp4', 

67 'w1', 

68 'w1u', 

69 'w1bd', 

70 'w1ro', 

71] 

72 

73 

74_xc_to_method = dict( 

75 pbe='pbepbe', 

76 pbe0='pbe1pbe', 

77 hse06='hseh1pbe', 

78 hse03='ohse2pbe', 

79 lda='svwn', # gaussian "knows about" LSDA, but maybe not LDA. 

80 tpss='tpsstpss', 

81 revtpss='revtpssrevtpss', 

82) 

83 

84_nuclear_prop_names = [ 

85 'spin', 

86 'zeff', 

87 'qmom', 

88 'nmagm', 

89 'znuc', 

90 'radnuclear', 

91 'iso', 

92] 

93 

94 

95def _get_molecule_spec(atoms, nuclear_props): 

96 """Generate the molecule specification section to write 

97 to the Gaussian input file, from the Atoms object and dict 

98 of nuclear properties""" 

99 molecule_spec = [] 

100 for i, atom in enumerate(atoms): 

101 symbol_section = atom.symbol + '(' 

102 # Check whether any nuclear properties of the atom have been set, 

103 # and if so, add them to the symbol section. 

104 nuclear_props_set = False 

105 for keyword, array in nuclear_props.items(): 

106 if array is not None and array[i] is not None: 

107 string = keyword + '=' + str(array[i]) + ', ' 

108 symbol_section += string 

109 nuclear_props_set = True 

110 

111 # Check whether the mass of the atom has been modified, 

112 # and if so, add it to the symbol section: 

113 mass_set = False 

114 symbol = atom.symbol 

115 expected_mass = atomic_masses_iupac2016[chemical_symbols.index(symbol)] 

116 if expected_mass != atoms[i].mass: 

117 mass_set = True 

118 string = 'iso' + '=' + str(atoms[i].mass) 

119 symbol_section += string 

120 

121 if nuclear_props_set or mass_set: 

122 symbol_section = symbol_section.strip(', ') 

123 symbol_section += ')' 

124 else: 

125 symbol_section = symbol_section.strip('(') 

126 

127 # Then attach the properties appropriately 

128 # this formatting was chosen for backwards compatibility reasons, but 

129 # it would probably be better to 

130 # 1) Ensure proper spacing between entries with explicit spaces 

131 # 2) Use fewer columns for the element 

132 # 3) Use 'e' (scientific notation) instead of 'f' for positions 

133 molecule_spec.append( 

134 '{:<10s}{:20.10f}{:20.10f}{:20.10f}'.format( 

135 symbol_section, *atom.position 

136 ) 

137 ) 

138 

139 # unit cell vectors, in case of periodic boundary conditions 

140 for ipbc, tv in zip(atoms.pbc, atoms.cell): 

141 if ipbc: 

142 molecule_spec.append('TV {:20.10f}{:20.10f}{:20.10f}'.format(*tv)) 

143 

144 molecule_spec.append('') 

145 

146 return molecule_spec 

147 

148 

149def _format_output_type(output_type): 

150 """Given a letter: output_type, return 

151 a string formatted for a gaussian input file""" 

152 # Change output type to P if it has been set to T, because ASE 

153 # does not support reading info from 'terse' output files. 

154 if output_type is None or output_type == '' or 't' in output_type.lower(): 

155 output_type = 'P' 

156 

157 return f'#{output_type}' 

158 

159 

160def _check_problem_methods(method): 

161 """Check method string for problem methods and warn appropriately""" 

162 if method.lower() in _problem_methods: 

163 warnings.warn( 

164 'The requested method, {}, is a composite method. Composite ' 

165 'methods do not have well-defined potential energy surfaces, ' 

166 'so the energies, forces, and other properties returned by ' 

167 'ASE may not be meaningful, or they may correspond to a ' 

168 'different geometry than the one provided. ' 

169 'Please use these methods with caution.'.format(method) 

170 ) 

171 

172 

173def _pop_link0_params(params): 

174 """Takes the params dict and returns a dict with the link0 keywords 

175 removed, and a list containing the link0 keywords and options 

176 to be written to the gaussian input file""" 

177 params = deepcopy(params) 

178 out = [] 

179 # Remove keywords from params, so they are not set again later in 

180 # route section 

181 for key in _link0_keys: 

182 if key not in params: 

183 continue 

184 val = params.pop(key) 

185 if not val or (isinstance(val, str) and key.lower() == val.lower()): 

186 out.append(f'%{key}') 

187 else: 

188 out.append(f'%{key}={val}') 

189 

190 # These link0 keywords have a slightly different syntax 

191 for key in _link0_special: 

192 if key not in params: 

193 continue 

194 val = params.pop(key) 

195 if not isinstance(val, str) and isinstance(val, Iterable): 

196 val = ' '.join(val) 

197 out.append(f'%{key} L{val}') 

198 

199 return params, out 

200 

201 

202def _format_method_basis(output_type, method, basis, fitting_basis): 

203 output_string = '' 

204 if basis and method and fitting_basis: 

205 output_string = '{} {}/{}/{} ! ASE formatted method and basis'.format( 

206 output_type, method, basis, fitting_basis 

207 ) 

208 elif basis and method: 

209 output_string = '{} {}/{} ! ASE formatted method and basis'.format( 

210 output_type, method, basis 

211 ) 

212 else: 

213 output_string = f'{output_type}' 

214 for value in [method, basis]: 

215 if value is not None: 

216 output_string += f' {value}' 

217 return output_string 

218 

219 

220def _format_route_params(params): 

221 """Get keywords and values from the params dictionary and return 

222 as a list of lines to add to the gaussian input file""" 

223 out = [] 

224 for key, val in params.items(): 

225 # assume bare keyword if val is falsey, i.e. '', None, False, etc. 

226 # also, for backwards compatibility: assume bare keyword if key and 

227 # val are the same 

228 if not val or (isinstance(val, str) and key.lower() == val.lower()): 

229 out.append(key) 

230 elif not isinstance(val, str) and isinstance(val, Iterable): 

231 out.append('{}({})'.format(key, ','.join(val))) 

232 else: 

233 out.append(f'{key}({val})') 

234 return out 

235 

236 

237def _format_addsec(addsec): 

238 """Format addsec string as a list of lines to be added to the gaussian 

239 input file.""" 

240 out = [] 

241 if addsec is not None: 

242 out.append('') 

243 if isinstance(addsec, str): 

244 out.append(addsec) 

245 elif isinstance(addsec, Iterable): 

246 out += list(addsec) 

247 return out 

248 

249 

250def _format_basis_set(basis, basisfile, basis_set): 

251 """Format either: the basis set filename (basisfile), the basis set file 

252 contents (from reading basisfile), or the basis_set text as a list of 

253 strings to be added to the gaussian input file.""" 

254 out = [] 

255 # if basis='gen', set basisfile. Either give a path to a basisfile, or 

256 # read in the provided file and paste it verbatim 

257 if basisfile is not None: 

258 if basisfile[0] == '@': 

259 out.append(basisfile) 

260 else: 

261 with open(basisfile) as fd: 

262 out.append(fd.read()) 

263 elif basis_set is not None: 

264 out.append(basis_set) 

265 else: 

266 if basis is not None and basis.lower() == 'gen': 

267 raise InputError('Please set basisfile or basis_set') 

268 return out 

269 

270 

271def write_gaussian_in( 

272 fd, 

273 atoms, 

274 properties=None, 

275 method=None, 

276 basis=None, 

277 fitting_basis=None, 

278 output_type='P', 

279 basisfile=None, 

280 basis_set=None, 

281 xc=None, 

282 charge=None, 

283 mult=None, 

284 extra=None, 

285 ioplist=None, 

286 addsec=None, 

287 spinlist=None, 

288 zefflist=None, 

289 qmomlist=None, 

290 nmagmlist=None, 

291 znuclist=None, 

292 radnuclearlist=None, 

293 **params, 

294): 

295 """ 

296 Generates a Gaussian input file 

297 

298 Parameters 

299 ----------- 

300 fd: file-like 

301 where the Gaussian input file will be written 

302 atoms: Atoms 

303 Structure to write to the input file 

304 properties: list 

305 Properties to calculate 

306 method: str 

307 Level of theory to use, e.g. ``hf``, ``ccsd``, ``mp2``, or ``b3lyp``. 

308 Overrides ``xc`` (see below). 

309 xc: str 

310 Level of theory to use. Translates several XC functionals from 

311 their common name (e.g. ``PBE``) to their internal Gaussian name 

312 (e.g. ``PBEPBE``). 

313 basis: str 

314 The basis set to use. If not provided, no basis set will be requested, 

315 which usually results in ``STO-3G``. Maybe omitted if basisfile is set 

316 (see below). 

317 fitting_basis: str 

318 The name of the fitting basis set to use. 

319 output_type: str 

320 Level of output to record in the Gaussian 

321 output file - this may be ``N``- normal or ``P`` - 

322 additional. 

323 basisfile: str 

324 The name of the basis file to use. If a value is provided, basis may 

325 be omitted (it will be automatically set to 'gen') 

326 basis_set: str 

327 The basis set definition to use. This is an alternative 

328 to basisfile, and would be the same as the contents 

329 of such a file. 

330 charge: int 

331 The system charge. If not provided, it will be automatically 

332 determined from the ``Atoms`` object’s initial_charges. 

333 mult: int 

334 The system multiplicity (``spin + 1``). If not provided, it will be 

335 automatically determined from the ``Atoms`` object’s 

336 ``initial_magnetic_moments``. 

337 extra: str 

338 Extra lines to be included in the route section verbatim. 

339 It should not be necessary to use this, but it is included for 

340 backwards compatibility. 

341 ioplist: list 

342 A collection of IOPs definitions to be included in the route line. 

343 addsec: str 

344 Text to be added after the molecular geometry specification, e.g. for 

345 defining masses with ``freq=ReadIso``. 

346 spinlist: list 

347 A list of nuclear spins to be added into the nuclear 

348 propeties section of the molecule specification. 

349 zefflist: list 

350 A list of effective charges to be added into the nuclear 

351 propeties section of the molecule specification. 

352 qmomlist: list 

353 A list of nuclear quadropole moments to be added into 

354 the nuclear propeties section of the molecule 

355 specification. 

356 nmagmlist: list 

357 A list of nuclear magnetic moments to be added into 

358 the nuclear propeties section of the molecule 

359 specification. 

360 znuclist: list 

361 A list of nuclear charges to be added into the nuclear 

362 propeties section of the molecule specification. 

363 radnuclearlist: list 

364 A list of nuclear radii to be added into the nuclear 

365 propeties section of the molecule specification. 

366 params: dict 

367 Contains any extra keywords and values that will be included in either 

368 the link0 section or route section of the gaussian input file. 

369 To be included in the link0 section, the keyword must be one of the 

370 following: ``mem``, ``chk``, ``oldchk``, ``schk``, ``rwf``, 

371 ``oldmatrix``, ``oldrawmatrix``, ``int``, ``d2e``, ``save``, 

372 ``nosave``, ``errorsave``, ``cpu``, ``nprocshared``, ``gpucpu``, 

373 ``lindaworkers``, ``usessh``, ``ssh``, ``debuglinda``. 

374 Any other keywords will be placed (along with their values) in the 

375 route section. 

376 """ 

377 

378 if properties is None: 

379 properties = ['energy'] 

380 params = deepcopy(params) 

381 

382 if properties is None: 

383 properties = ['energy'] 

384 

385 output_type = _format_output_type(output_type) 

386 

387 # basis can be omitted if basisfile is provided 

388 if basis is None: 

389 if basisfile is not None or basis_set is not None: 

390 basis = 'gen' 

391 

392 # determine method from xc if it is provided 

393 if method is None: 

394 if xc is not None: 

395 method = _xc_to_method.get(xc.lower(), xc) 

396 

397 # If the user requests a problematic method, rather than raising an error 

398 # or proceeding blindly, give the user a warning that the results parsed 

399 # by ASE may not be meaningful. 

400 if method is not None: 

401 _check_problem_methods(method) 

402 

403 # determine charge from initial charges if not passed explicitly 

404 if charge is None: 

405 charge = atoms.get_initial_charges().sum() 

406 

407 # determine multiplicity from initial magnetic moments 

408 # if not passed explicitly 

409 if mult is None: 

410 mult = atoms.get_initial_magnetic_moments().sum() + 1 

411 

412 # set up link0 arguments 

413 out = [] 

414 params, link0_list = _pop_link0_params(params) 

415 out.extend(link0_list) 

416 

417 # begin route line 

418 # note: unlike in old calculator, each route keyword is put on its own 

419 # line. 

420 out.append(_format_method_basis(output_type, method, basis, fitting_basis)) 

421 

422 # If the calculator's parameter dictionary contains an isolist, we ignore 

423 # this - it is up to the user to attach this info as the atoms' masses 

424 # if they wish for it to be used: 

425 params.pop('isolist', None) 

426 

427 # Any params left will belong in the route section of the file: 

428 out.extend(_format_route_params(params)) 

429 

430 if ioplist is not None: 

431 out.append('IOP(' + ', '.join(ioplist) + ')') 

432 

433 # raw list of explicit keywords for backwards compatibility 

434 if extra is not None: 

435 out.append(extra) 

436 

437 # Add 'force' iff the user requested forces, since Gaussian crashes when 

438 # 'force' is combined with certain other keywords such as opt and irc. 

439 if 'forces' in properties and 'force' not in params: 

440 out.append('force') 

441 

442 # header, charge, and mult 

443 out += [ 

444 '', 

445 'Gaussian input prepared by ASE', 

446 '', 

447 f'{charge:.0f} {mult:.0f}', 

448 ] 

449 

450 # make dict of nuclear properties: 

451 nuclear_props = { 

452 'spin': spinlist, 

453 'zeff': zefflist, 

454 'qmom': qmomlist, 

455 'nmagm': nmagmlist, 

456 'znuc': znuclist, 

457 'radnuclear': radnuclearlist, 

458 } 

459 nuclear_props = {k: v for k, v in nuclear_props.items() if v is not None} 

460 

461 # atomic positions and nuclear properties: 

462 molecule_spec = _get_molecule_spec(atoms, nuclear_props) 

463 for line in molecule_spec: 

464 out.append(line) 

465 

466 out.extend(_format_basis_set(basis, basisfile, basis_set)) 

467 

468 out.extend(_format_addsec(addsec)) 

469 

470 out += ['', ''] 

471 fd.write('\n'.join(out)) 

472 

473 

474# Regexp for reading an input file: 

475 

476_re_link0 = re.compile(r'^\s*%([^\=\)\(!]+)=?([^\=\)\(!]+)?(!.+)?') 

477# Link0 lines are in the format: 

478# '% keyword = value' or '% keyword' 

479# (with or without whitespaces) 

480 

481_re_output_type = re.compile(r'^\s*#\s*([NPTnpt]?)\s*') 

482# The start of the route section begins with a '#', and then may 

483# be followed by the desired level of output in the output file: P, N or T. 

484 

485_re_method_basis = re.compile( 

486 r'\s*([\w-]+)\s*\/([^/=!]+)([\/]([^!]+))?\s*(!.+)?' 

487) 

488# Matches method, basis and optional fitting basis in the format: 

489# method/basis/fitting_basis ! comment 

490# They will appear in this format if the Gaussian file has been generated 

491# by ASE using a calculator with the basis and method keywords set. 

492 

493_re_chgmult = re.compile(r'^(\s*[+-]?\d+(?:,\s*|\s+)[+-]?\d+\s*){1,}$') 

494# This is a bit more complex of a regex than we typically want, but it 

495# can be difficult to determine whether a line contains the charge and 

496# multiplicity, rather than just another route keyword. By making sure 

497# that the line contains exactly an even number of *integers*, separated by 

498# either a comma (and possibly whitespace) or some amount of whitespace, we 

499# can be more confident that we've actually found the charge and multiplicity. 

500# Note that in recent versions of Gaussian, the gjf file can contain fragments, 

501# where you can give a charge and multiplicity to each fragment. This pattern 

502# will allow ASE to read this line in for the charge and multiplicity, however 

503# the _get_charge_mult method will only input the first two integers that 

504# always gives the overall charge and multiplcity for the full chemical system. 

505# The charge and multiplicity of the fragments will be ignored in the 

506# _get_charge_mult method. 

507 

508_re_nuclear_props = re.compile(r'\(([^\)]+)\)') 

509# Matches the nuclear properties, which are contained in parantheses. 

510 

511# The following methods are used in GaussianConfiguration's 

512# parse_gaussian_input method: 

513 

514 

515def _get_link0_param(link0_match): 

516 """Gets link0 keyword and option from a re.Match and returns them 

517 in a dictionary format""" 

518 value = link0_match.group(2) 

519 if value is not None: 

520 value = value.strip() 

521 else: 

522 value = '' 

523 return {link0_match.group(1).lower().strip(): value.lower()} 

524 

525 

526def _get_all_link0_params(link0_section): 

527 """Given a string link0_section which contains the link0 

528 section of a gaussian input file, returns a dictionary of 

529 keywords and values""" 

530 parameters = {} 

531 for line in link0_section: 

532 link0_match = _re_link0.match(line) 

533 link0_param = _get_link0_param(link0_match) 

534 if link0_param is not None: 

535 parameters.update(link0_param) 

536 return parameters 

537 

538 

539def _convert_to_symbol(string): 

540 """Converts an input string into a format 

541 that can be input to the 'symbol' parameter of an 

542 ASE Atom object (can be a chemical symbol (str) 

543 or an atomic number (int)). 

544 This is achieved by either stripping any 

545 integers from the string, or converting a string 

546 containing an atomic number to integer type""" 

547 symbol = _validate_symbol_string(string) 

548 if symbol.isnumeric(): 

549 atomic_number = int(symbol) 

550 symbol = chemical_symbols[atomic_number] 

551 else: 

552 match = re.match(r'([A-Za-z]+)', symbol) 

553 symbol = match.group(1) 

554 return symbol 

555 

556 

557def _validate_symbol_string(string): 

558 if '-' in string: 

559 raise ParseError( 

560 'ERROR: Could not read the Gaussian input file, as' 

561 ' molecule specifications for molecular mechanics ' 

562 'calculations are not supported.' 

563 ) 

564 return string 

565 

566 

567def _get_key_value_pairs(line): 

568 """Read line of a gaussian input file with keywords and options 

569 separated according to the rules of the route section. 

570 

571 Parameters 

572 ---------- 

573 line (string) 

574 A line of a gaussian input file. 

575 

576 Returns 

577 --------- 

578 params (dict) 

579 Contains the keywords and options found in the line. 

580 """ 

581 params = {} 

582 line = line.strip(' #') 

583 line = line.split('!')[0] # removes any comments 

584 # First, get the keywords and options sepatated with 

585 # parantheses: 

586 match_iterator = re.finditer(r'\(([^\)]+)\)', line) 

587 index_ranges = [] 

588 for match in match_iterator: 

589 index_range = [match.start(0), match.end(0)] 

590 options = match.group(1) 

591 # keyword is last word in previous substring: 

592 keyword_string = line[: match.start(0)] 

593 keyword_match_iter = [ 

594 k 

595 for k in re.finditer(r'[^\,/\s]+', keyword_string) 

596 if k.group() != '=' 

597 ] 

598 keyword = keyword_match_iter[-1].group().strip(' =') 

599 index_range[0] = keyword_match_iter[-1].start() 

600 params.update({keyword.lower(): options.lower()}) 

601 index_ranges.append(index_range) 

602 

603 # remove from the line the keywords and options that we have saved: 

604 index_ranges.reverse() 

605 for index_range in index_ranges: 

606 start = index_range[0] 

607 stop = index_range[1] 

608 line = line[0:start:] + line[stop + 1 :] 

609 

610 # Next, get the keywords and options separated with 

611 # an equals sign, and those without an equals sign 

612 # must be keywords without options: 

613 

614 # remove any whitespaces around '=': 

615 line = re.sub(r'\s*=\s*', '=', line) 

616 line = [x for x in re.split(r'[\s,\/]', line) if x != ''] 

617 

618 for s in line: 

619 if '=' in s: 

620 s = s.split('=') 

621 keyword = s.pop(0) 

622 options = s.pop(0) 

623 params.update({keyword.lower(): options.lower()}) 

624 else: 

625 if len(s) > 0: 

626 params.update({s.lower(): None}) 

627 

628 return params 

629 

630 

631def _get_route_params(line): 

632 """Reads keywords and values from a line in 

633 a Gaussian input file's route section, 

634 and returns them as a dictionary""" 

635 method_basis_match = _re_method_basis.match(line) 

636 if method_basis_match: 

637 params = {} 

638 ase_gen_comment = '! ASE formatted method and basis' 

639 if method_basis_match.group(5) == ase_gen_comment: 

640 params['method'] = method_basis_match.group(1).strip().lower() 

641 params['basis'] = method_basis_match.group(2).strip().lower() 

642 if method_basis_match.group(4): 

643 params['fitting_basis'] = ( 

644 method_basis_match.group(4).strip().lower() 

645 ) 

646 return params 

647 

648 return _get_key_value_pairs(line) 

649 

650 

651def _get_all_route_params(route_section): 

652 """Given a string: route_section which contains the route 

653 section of a gaussian input file, returns a dictionary of 

654 keywords and values""" 

655 parameters = {} 

656 

657 for line in route_section: 

658 output_type_match = _re_output_type.match(line) 

659 if not parameters.get('output_type') and output_type_match: 

660 line = line.strip(output_type_match.group(0)) 

661 parameters.update( 

662 {'output_type': output_type_match.group(1).lower()} 

663 ) 

664 # read route section 

665 route_params = _get_route_params(line) 

666 if route_params is not None: 

667 parameters.update(route_params) 

668 return parameters 

669 

670 

671def _get_charge_mult(chgmult_section): 

672 """return a dict with the charge and multiplicity from 

673 a list chgmult_section that contains the charge and multiplicity 

674 line, read from a gaussian input file""" 

675 chgmult_match = _re_chgmult.match(str(chgmult_section)) 

676 try: 

677 chgmult = chgmult_match.group(0).split() 

678 return {'charge': int(chgmult[0]), 'mult': int(chgmult[1])} 

679 except (IndexError, AttributeError): 

680 raise ParseError( 

681 'ERROR: Could not read the charge and ' 

682 'multiplicity from the Gaussian input ' 

683 'file. There must be an even number of ' 

684 'integers separated with whitespace or ' 

685 'a comma, where the first two integers ' 

686 'must be the overall charge and overall ' 

687 'multiplicity of the chemical system, ' 

688 'respectively.' 

689 ) 

690 

691 

692def _get_nuclear_props(line): 

693 """Reads any info in parantheses in the line and returns 

694 a dictionary of the nuclear properties.""" 

695 nuclear_props_match = _re_nuclear_props.search(line) 

696 nuclear_props = {} 

697 if nuclear_props_match: 

698 nuclear_props = _get_key_value_pairs(nuclear_props_match.group(1)) 

699 updated_nuclear_props = {} 

700 for key, value in nuclear_props.items(): 

701 if value.isnumeric(): 

702 value = int(value) 

703 else: 

704 value = float(value) 

705 if key not in _nuclear_prop_names: 

706 if 'fragment' in key: 

707 warnings.warn('Fragments are not currently supported.') 

708 warnings.warn( 

709 'The following nuclear properties ' 

710 'could not be saved: {}'.format({key: value}) 

711 ) 

712 else: 

713 updated_nuclear_props[key] = value 

714 nuclear_props = updated_nuclear_props 

715 

716 for k in _nuclear_prop_names: 

717 if k not in nuclear_props: 

718 nuclear_props[k] = None 

719 

720 return nuclear_props 

721 

722 

723def _get_atoms_info(line): 

724 """Returns the symbol and position of an atom from a line 

725 in the molecule specification section""" 

726 nuclear_props_match = _re_nuclear_props.search(line) 

727 if nuclear_props_match: 

728 line = line.replace(nuclear_props_match.group(0), '') 

729 tokens = line.split() 

730 symbol = _convert_to_symbol(tokens[0]) 

731 pos = list(tokens[1:]) 

732 

733 return symbol, pos 

734 

735 

736def _get_cartesian_atom_coords(symbol, pos): 

737 """Returns the coordinates: pos as a list of floats if they 

738 are cartesian, and not in z-matrix format""" 

739 if len(pos) < 3 or (pos[0] == '0' and symbol != 'TV'): 

740 # In this case, we have a z-matrix definition, so 

741 # no cartesian coords. 

742 return None 

743 elif len(pos) > 3: 

744 raise ParseError( 

745 'ERROR: Gaussian input file could ' 

746 'not be read as freeze codes are not' 

747 ' supported. If using cartesian ' 

748 'coordinates, these must be ' 

749 'given as 3 numbers separated ' 

750 'by whitespace.' 

751 ) 

752 else: 

753 try: 

754 return list(map(float, pos)) 

755 except ValueError: 

756 raise ParseError( 

757 'ERROR: Molecule specification in' 

758 'Gaussian input file could not be read' 

759 ) 

760 

761 

762def _get_zmatrix_line(line): 

763 """Converts line into the format needed for it to 

764 be added to the z-matrix contents""" 

765 line_list = line.split() 

766 if len(line_list) == 8 and line_list[7] == '1': 

767 raise ParseError( 

768 'ERROR: Could not read the Gaussian input file' 

769 ', as the alternative Z-matrix format using ' 

770 'two bond angles instead of a bond angle and ' 

771 'a dihedral angle is not supported.' 

772 ) 

773 return line.strip() + '\n' 

774 

775 

776def _read_zmatrix(zmatrix_contents, zmatrix_vars=None): 

777 """Reads a z-matrix (zmatrix_contents) using its list of variables 

778 (zmatrix_vars), and returns atom positions and symbols""" 

779 try: 

780 atoms = parse_zmatrix(zmatrix_contents, defs=zmatrix_vars) 

781 except (ValueError, RuntimeError) as e: 

782 raise ParseError( 

783 'Failed to read Z-matrix from Gaussian input file: ', e 

784 ) 

785 except KeyError as e: 

786 raise ParseError( 

787 'Failed to read Z-matrix from ' 

788 'Gaussian input file, as symbol: {}' 

789 'could not be recognised. Please make ' 

790 'sure you use element symbols, not ' 

791 'atomic numbers in the element labels.'.format(e) 

792 ) 

793 positions = atoms.positions 

794 symbols = atoms.get_chemical_symbols() 

795 return positions, symbols 

796 

797 

798def _get_nuclear_props_for_all_atoms(nuclear_props): 

799 """Returns the nuclear properties for all atoms as a dictionary, 

800 in the format needed for it to be added to the parameters dictionary.""" 

801 params = {k + 'list': [] for k in _nuclear_prop_names} 

802 for dictionary in nuclear_props: 

803 for key, value in dictionary.items(): 

804 params[key + 'list'].append(value) 

805 

806 for key, array in params.items(): 

807 values_set = False 

808 for value in array: 

809 if value is not None: 

810 values_set = True 

811 if not values_set: 

812 params[key] = None 

813 return params 

814 

815 

816def _get_atoms_from_molspec(molspec_section): 

817 """Takes a string: molspec_section which contains the molecule 

818 specification section of a gaussian input file, and returns an atoms 

819 object that represents this.""" 

820 # These will contain info that will be attached to the Atoms object: 

821 symbols = [] 

822 positions = [] 

823 pbc = np.zeros(3, dtype=bool) 

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

825 npbc = 0 

826 

827 # Will contain a dictionary of nuclear properties for each atom, 

828 # that will later be saved to the parameters dict: 

829 nuclear_props = [] 

830 

831 # Info relating to the z-matrix definition (if set) 

832 zmatrix_type = False 

833 zmatrix_contents = '' 

834 zmatrix_var_section = False 

835 zmatrix_vars = '' 

836 

837 for line in molspec_section: 

838 # Remove any comments and replace '/' and ',' with whitespace, 

839 # as these are equivalent: 

840 line = line.split('!')[0].replace('/', ' ').replace(',', ' ') 

841 if line.split(): 

842 if zmatrix_type: 

843 # Save any variables set when defining the z-matrix: 

844 if zmatrix_var_section: 

845 zmatrix_vars += line.strip() + '\n' 

846 continue 

847 elif 'variables' in line.lower(): 

848 zmatrix_var_section = True 

849 continue 

850 elif 'constants' in line.lower(): 

851 zmatrix_var_section = True 

852 warnings.warn( 

853 'Constants in the optimisation are ' 

854 'not currently supported. Instead ' 

855 'setting constants as variables.' 

856 ) 

857 continue 

858 

859 symbol, pos = _get_atoms_info(line) 

860 current_nuclear_props = _get_nuclear_props(line) 

861 

862 if not zmatrix_type: 

863 pos = _get_cartesian_atom_coords(symbol, pos) 

864 if pos is None: 

865 zmatrix_type = True 

866 

867 if symbol.upper() == 'TV' and pos is not None: 

868 pbc[npbc] = True 

869 cell[npbc] = pos 

870 npbc += 1 

871 else: 

872 nuclear_props.append(current_nuclear_props) 

873 if not zmatrix_type: 

874 symbols.append(symbol) 

875 positions.append(pos) 

876 

877 if zmatrix_type: 

878 zmatrix_contents += _get_zmatrix_line(line) 

879 

880 # Now that we are past the molecule spec. section, we can read 

881 # the entire z-matrix (if set): 

882 if len(positions) == 0: 

883 if zmatrix_type: 

884 if zmatrix_vars == '': 

885 zmatrix_vars = None 

886 positions, symbols = _read_zmatrix(zmatrix_contents, zmatrix_vars) 

887 

888 try: 

889 atoms = Atoms(symbols, positions, pbc=pbc, cell=cell) 

890 except (IndexError, ValueError, KeyError) as e: 

891 raise ParseError( 

892 'ERROR: Could not read the Gaussian input file, ' 

893 'due to a problem with the molecule ' 

894 'specification: {}'.format(e) 

895 ) 

896 

897 nuclear_props = _get_nuclear_props_for_all_atoms(nuclear_props) 

898 

899 return atoms, nuclear_props 

900 

901 

902def _get_readiso_param(parameters): 

903 """Returns a tuple containing the frequency 

904 keyword and its options, if the frequency keyword is 

905 present in parameters and ReadIso is one of its options""" 

906 freq_options = parameters.get('freq', None) 

907 if freq_options: 

908 freq_name = 'freq' 

909 else: 

910 freq_options = parameters.get('frequency', None) 

911 freq_name = 'frequency' 

912 if freq_options is not None: 

913 if ('readiso' or 'readisotopes') in freq_options: 

914 return freq_name, freq_options 

915 return None, None 

916 

917 

918def _get_readiso_info(line, parameters): 

919 """Reads the temperature, pressure and scale from the first line 

920 of a ReadIso section of a Gaussian input file. Returns these in 

921 a dictionary.""" 

922 readiso_params = {} 

923 if _get_readiso_param(parameters)[0] is not None: 

924 # when count_iso is 0 we are in the line where 

925 # temperature, pressure, [scale] is saved 

926 line = line.replace('[', '').replace(']', '') 

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

928 try: 

929 readiso_params['temperature'] = tokens[0] 

930 readiso_params['pressure'] = tokens[1] 

931 readiso_params['scale'] = tokens[2] 

932 except IndexError: 

933 pass 

934 if readiso_params != {}: 

935 return readiso_params 

936 

937 

938def _delete_readiso_param(parameters): 

939 """Removes the readiso parameter from the parameters dict""" 

940 parameters = deepcopy(parameters) 

941 freq_name, freq_options = _get_readiso_param(parameters) 

942 if freq_name is not None: 

943 if 'readisotopes' in freq_options: 

944 iso_name = 'readisotopes' 

945 else: 

946 iso_name = 'readiso' 

947 freq_options = [ 

948 v.group() for v in re.finditer(r'[^\,/\s]+', freq_options) 

949 ] 

950 freq_options.remove(iso_name) 

951 new_freq_options = '' 

952 for v in freq_options: 

953 new_freq_options += v + ' ' 

954 if new_freq_options == '': 

955 new_freq_options = None 

956 else: 

957 new_freq_options = new_freq_options.strip() 

958 parameters[freq_name] = new_freq_options 

959 return parameters 

960 

961 

962def _update_readiso_params(parameters, symbols): 

963 """Deletes the ReadIso option from the route section as we 

964 write out the masses in the nuclear properties section 

965 instead of the ReadIso section. 

966 Ensures the masses array is the same length as the 

967 symbols array. This is necessary due to the way the 

968 ReadIso section is defined: 

969 The mass of each atom is listed on a separate line, in 

970 order of appearance in the molecule spec. A blank line 

971 indicates not to modify the mass for that atom. 

972 But you do not have to leave blank lines equal to the 

973 remaining atoms after you finsihed setting masses. 

974 E.g. if you had 10 masses and only want to set the mass 

975 for the first atom, you don't have to leave 9 blank lines 

976 after it. 

977 """ 

978 parameters = _delete_readiso_param(parameters) 

979 if parameters.get('isolist') is not None: 

980 if len(parameters['isolist']) < len(symbols): 

981 for _ in range(len(symbols) - len(parameters['isolist'])): 

982 parameters['isolist'].append(None) 

983 if all(m is None for m in parameters['isolist']): 

984 parameters['isolist'] = None 

985 

986 return parameters 

987 

988 

989def _validate_params(parameters): 

990 """Checks whether all of the required parameters exist in the 

991 parameters dict and whether it contains any unsupported settings 

992 """ 

993 # Check for unsupported settings 

994 unsupported_settings = { 

995 'z-matrix', 

996 'modredun', 

997 'modredundant', 

998 'addredundant', 

999 'addredun', 

1000 'readopt', 

1001 'rdopt', 

1002 } 

1003 

1004 for s in unsupported_settings: 

1005 for v in parameters.values(): 

1006 if v is not None and s in str(v): 

1007 raise ParseError( 

1008 'ERROR: Could not read the Gaussian input file' 

1009 ', as the option: {} is currently unsupported.'.format(s) 

1010 ) 

1011 

1012 for k in list(parameters.keys()): 

1013 if 'popt' in k: 

1014 parameters['opt'] = parameters.pop(k) 

1015 warnings.warn( 

1016 'The option {} is currently unsupported. ' 

1017 'This has been replaced with {}.'.format('POpt', 'opt') 

1018 ) 

1019 return 

1020 

1021 

1022def _get_extra_section_params(extra_section, parameters, atoms): 

1023 """Takes a list of strings: extra_section, which contains 

1024 the 'extra' lines in a gaussian input file. Also takes the parameters 

1025 that have been read so far, and the atoms that have been read from the 

1026 file. 

1027 Returns an updated version of the parameters dict, containing details from 

1028 this extra section. This may include the basis set definition or filename, 

1029 and/or the readiso section.""" 

1030 

1031 new_parameters = deepcopy(parameters) 

1032 # Will store the basis set definition (if set): 

1033 basis_set = '' 

1034 # This will indicate whether we have a readiso section: 

1035 readiso = _get_readiso_param(new_parameters)[0] 

1036 # This will indicate which line of the readiso section we are reading: 

1037 count_iso = 0 

1038 readiso_masses = [] 

1039 

1040 for line in extra_section: 

1041 if line.split(): 

1042 # check that the line isn't just a comment 

1043 if line.split()[0] == '!': 

1044 continue 

1045 line = line.strip().split('!')[0] 

1046 

1047 if len(line) > 0 and line[0] == '@': 

1048 # If the name of a basis file is specified, this line 

1049 # begins with a '@' 

1050 new_parameters['basisfile'] = line 

1051 elif readiso and count_iso < len(atoms.symbols) + 1: 

1052 # The ReadIso section has 1 more line than the number of 

1053 # symbols 

1054 if count_iso == 0 and line != '\n': 

1055 # The first line in the readiso section contains the 

1056 # temperature, pressure, scale. Here we save this: 

1057 readiso_info = _get_readiso_info(line, new_parameters) 

1058 if readiso_info is not None: 

1059 new_parameters.update(readiso_info) 

1060 # If the atom masses were set in the nuclear properties 

1061 # section, they will be overwritten by the ReadIso 

1062 # section 

1063 readiso_masses = [] 

1064 count_iso += 1 

1065 elif count_iso > 0: 

1066 # The remaining lines in the ReadIso section are 

1067 # the masses of the atoms 

1068 try: 

1069 readiso_masses.append(float(line)) 

1070 except ValueError: 

1071 readiso_masses.append(None) 

1072 count_iso += 1 

1073 else: 

1074 # If the rest of the file is not the ReadIso section, 

1075 # then it must be the definition of the basis set. 

1076 if ( 

1077 new_parameters.get('basis', '') == 'gen' 

1078 or 'gen' in new_parameters 

1079 ): 

1080 if line.strip() != '': 

1081 basis_set += line + '\n' 

1082 

1083 if readiso: 

1084 new_parameters['isolist'] = readiso_masses 

1085 new_parameters = _update_readiso_params(new_parameters, atoms.symbols) 

1086 

1087 # Saves the basis set definition to the parameters array if 

1088 # it has been set: 

1089 if basis_set != '': 

1090 new_parameters['basis_set'] = basis_set 

1091 new_parameters['basis'] = 'gen' 

1092 new_parameters.pop('gen', None) 

1093 

1094 return new_parameters 

1095 

1096 

1097def _get_gaussian_in_sections(fd): 

1098 """Reads a gaussian input file and returns 

1099 a dictionary of the sections of the file - each dictionary 

1100 value is a list of strings - each string is a line in that 

1101 section.""" 

1102 # These variables indicate which section of the 

1103 # input file is currently being read: 

1104 route_section = False 

1105 atoms_section = False 

1106 atoms_saved = False 

1107 # Here we will store the sections of the file in a dictionary, 

1108 # as lists of strings 

1109 gaussian_sections = { 

1110 'link0': [], 

1111 'route': [], 

1112 'charge_mult': [], 

1113 'mol_spec': [], 

1114 'extra': [], 

1115 } 

1116 

1117 for line in fd: 

1118 line = line.strip(' ') 

1119 link0_match = _re_link0.match(line) 

1120 output_type_match = _re_output_type.match(line) 

1121 chgmult_match = _re_chgmult.match(line) 

1122 if link0_match: 

1123 gaussian_sections['link0'].append(line) 

1124 # The first blank line appears at the end of the route section 

1125 # and a blank line appears at the end of the atoms section: 

1126 elif line == '\n' and (route_section or atoms_section): 

1127 route_section = False 

1128 atoms_section = False 

1129 elif output_type_match or route_section: 

1130 route_section = True 

1131 gaussian_sections['route'].append(line) 

1132 elif chgmult_match: 

1133 gaussian_sections['charge_mult'] = line 

1134 # After the charge and multiplicty have been set, the 

1135 # molecule specification section of the input file begins: 

1136 atoms_section = True 

1137 elif atoms_section: 

1138 gaussian_sections['mol_spec'].append(line) 

1139 atoms_saved = True 

1140 elif atoms_saved: 

1141 # Next we read the other sections below the molecule spec. 

1142 # This may include the ReadIso section and the basis set 

1143 # definition or filename 

1144 gaussian_sections['extra'].append(line) 

1145 

1146 return gaussian_sections 

1147 

1148 

1149class GaussianConfiguration: 

1150 def __init__(self, atoms, parameters): 

1151 self.atoms = atoms.copy() 

1152 self.parameters = deepcopy(parameters) 

1153 

1154 def get_atoms(self): 

1155 return self.atoms 

1156 

1157 def get_parameters(self): 

1158 return self.parameters 

1159 

1160 def get_calculator(self): 

1161 # Explicitly set parameters that must for security reasons not be 

1162 # taken from file: 

1163 calc = Gaussian( 

1164 atoms=self.atoms, 

1165 command=None, 

1166 restart=None, 

1167 ignore_bad_restart_file=Calculator._deprecated, 

1168 label='Gaussian', 

1169 directory='.', 

1170 **self.parameters, 

1171 ) 

1172 return calc 

1173 

1174 @staticmethod 

1175 def parse_gaussian_input(fd): 

1176 """Reads a gaussian input file into an atoms object and 

1177 parameters dictionary. 

1178 

1179 Parameters 

1180 ---------- 

1181 fd: file-like 

1182 Contains the contents of a gaussian input file 

1183 

1184 Returns 

1185 --------- 

1186 GaussianConfiguration 

1187 Contains an atoms object created using the structural 

1188 information from the input file. 

1189 Contains a parameters dictionary, which stores any 

1190 keywords and options found in the link-0 and route 

1191 sections of the input file. 

1192 """ 

1193 # The parameters dict to attach to the calculator 

1194 parameters = {} 

1195 

1196 file_sections = _get_gaussian_in_sections(fd) 

1197 

1198 # Update the parameters dictionary with the keywords and values 

1199 # from each section of the input file: 

1200 parameters.update(_get_all_link0_params(file_sections['link0'])) 

1201 parameters.update(_get_all_route_params(file_sections['route'])) 

1202 parameters.update(_get_charge_mult(file_sections['charge_mult'])) 

1203 atoms, nuclear_props = _get_atoms_from_molspec( 

1204 file_sections['mol_spec'] 

1205 ) 

1206 parameters.update(nuclear_props) 

1207 parameters.update( 

1208 _get_extra_section_params(file_sections['extra'], parameters, atoms) 

1209 ) 

1210 

1211 _validate_params(parameters) 

1212 

1213 return GaussianConfiguration(atoms, parameters) 

1214 

1215 

1216def read_gaussian_in(fd, attach_calculator=False): 

1217 """ 

1218 Reads a gaussian input file and returns an Atoms object. 

1219 

1220 Parameters 

1221 ---------- 

1222 fd: file-like 

1223 Contains the contents of a gaussian input file 

1224 

1225 attach_calculator: bool 

1226 When set to ``True``, a Gaussian calculator will be 

1227 attached to the Atoms object which is returned. 

1228 This will mean that additional information is read 

1229 from the input file (see below for details). 

1230 

1231 Returns 

1232 ---------- 

1233 Atoms 

1234 An Atoms object containing the following information that has been 

1235 read from the input file: symbols, positions, cell. 

1236 

1237 Notes 

1238 ---------- 

1239 Gaussian input files can be read where the atoms' locations are set with 

1240 cartesian coordinates or as a z-matrix. Variables may be used in the 

1241 z-matrix definition, but currently setting constants for constraining 

1242 a geometry optimisation is not supported. Note that the `alternative` 

1243 z-matrix definition where two bond angles are set instead of a bond angle 

1244 and a dihedral angle is not currently supported. 

1245 

1246 If the parameter ``attach_calculator`` is set to ``True``, then the Atoms 

1247 object is returned with a Gaussian calculator attached. 

1248 

1249 This Gaussian calculator will contain a parameters dictionary which will 

1250 contain the Link 0 commands and the options and keywords set in the route 

1251 section of the Gaussian input file, as well as: 

1252 

1253 • The charge and multiplicity 

1254 

1255 • The selected level of output 

1256 

1257 • The method, basis set and (optional) fitting basis set. 

1258 

1259 • Basis file name/definition if set 

1260 

1261 • Nuclear properties 

1262 

1263 • Masses set in the nuclear properties section or in the ReadIsotopes 

1264 section (if ``freq=ReadIso`` is set). These will be saved in an array 

1265 with keyword ``isolist``, in the parameters dictionary. For these to 

1266 actually be used in calculations and/or written out to input files, 

1267 the Atoms object's masses must be manually updated to these values 

1268 (this is not done automatically) 

1269 

1270 If the Gaussian input file has been generated by ASE's 

1271 ``write_gaussian_in`` method, then the basis set, method and fitting 

1272 basis will be saved under the ``basis``, ``method`` and ``fitting_basis`` 

1273 keywords in the parameters dictionary. Otherwise they are saved as 

1274 keywords in the parameters dict. 

1275 

1276 Currently this does not support reading of any other sections which would 

1277 be found below the molecule specification that have not been mentioned 

1278 here (such as the ModRedundant section). 

1279 """ 

1280 gaussian_input = GaussianConfiguration.parse_gaussian_input(fd) 

1281 atoms = gaussian_input.get_atoms() 

1282 

1283 if attach_calculator: 

1284 atoms.calc = gaussian_input.get_calculator() 

1285 

1286 return atoms 

1287 

1288 

1289# In the interest of using the same RE for both atomic positions and forces, 

1290# we make one of the columns optional. That's because atomic positions have 

1291# 6 columns, while forces only has 5 columns. Otherwise they are very similar. 

1292_re_atom = re.compile(r'^\s*\S+\s+(\S+)\s+(?:\S+\s+)?(\S+)\s+(\S+)\s+(\S+)\s*$') 

1293_re_forceblock = re.compile(r'^\s*Center\s+Atomic\s+Forces\s+\S+\s*$') 

1294_re_l716 = re.compile(r'^\s*\(Enter .+l716.exe\)$') 

1295 

1296 

1297def _compare_merge_configs(configs, new): 

1298 """Append new to configs if it contains a new geometry or new data. 

1299 

1300 Gaussian sometimes repeats a geometry, for example at the end of an 

1301 optimization, or when a user requests vibrational frequency 

1302 analysis in the same calculation as a geometry optimization. 

1303 

1304 In those cases, rather than repeating the structure in the list of 

1305 returned structures, try to merge results if doing so doesn't change 

1306 any previously calculated values. If that's not possible, then create 

1307 a new "image" with the new results. 

1308 """ 

1309 if not configs: 

1310 configs.append(new) 

1311 return 

1312 

1313 old = configs[-1] 

1314 

1315 if old != new: 

1316 configs.append(new) 

1317 return 

1318 

1319 oldres = old.calc.results 

1320 newres = new.calc.results 

1321 common_keys = set(oldres).intersection(newres) 

1322 

1323 for key in common_keys: 

1324 if np.any(oldres[key] != newres[key]): 

1325 configs.append(new) 

1326 return 

1327 oldres.update(newres) 

1328 

1329 

1330def _read_charges(fd): 

1331 fd.readline() 

1332 qs = [] 

1333 ms = [] 

1334 for line in fd: 

1335 if not line.strip()[0].isdigit(): 

1336 break 

1337 qs.append(float(line.split()[2])) 

1338 if len(line.split()) > 3: 

1339 ms.append(float(line.split()[3])) 

1340 return {'charges': qs, 'magmoms': ms} if ms else {'charges': qs} 

1341 

1342 

1343def read_gaussian_out(fd, index=-1): 

1344 """Reads a gaussian output file and returns an Atoms object.""" 

1345 configs = [] 

1346 atoms = None 

1347 energy = None 

1348 results = {} 

1349 orientation = None # Orientation of the coordinates stored in atoms 

1350 for line in fd: 

1351 line = line.strip() 

1352 if line.startswith(r'1\1\GINC'): 

1353 # We've reached the "archive" block at the bottom, stop parsing 

1354 break 

1355 

1356 if ( 

1357 line == 'Input orientation:' 

1358 or line == 'Z-Matrix orientation:' 

1359 or line == 'Standard orientation:' 

1360 ): 

1361 if atoms is not None: 

1362 # Add configuration to the currently-parsed list 

1363 # only after an energy or force has been parsed 

1364 # (we assume these are in the output file) 

1365 if energy is None: 

1366 continue 

1367 # "atoms" should store the first geometry encountered 

1368 # in the input file which is often the input orientation, 

1369 # which is the orientation for forces. 

1370 # If there are forces and the orientation of atoms is not 

1371 # the input coordinate system, warn the user 

1372 if orientation != 'Input' and 'forces' in results: 

1373 logger.warning( 

1374 'Configuration geometry is not in the input' 

1375 f'orientation. It is {orientation}' 

1376 ) 

1377 calc = SinglePointCalculator(atoms, energy=energy, **results) 

1378 atoms.calc = calc 

1379 _compare_merge_configs(configs, atoms) 

1380 atoms = None 

1381 orientation = line.split()[0] # Store the orientation 

1382 energy = None 

1383 results = {} 

1384 

1385 numbers = [] 

1386 positions = [] 

1387 pbc = np.zeros(3, dtype=bool) 

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

1389 npbc = 0 

1390 # skip 4 irrelevant lines 

1391 for _ in range(4): 

1392 fd.readline() 

1393 while True: 

1394 match = _re_atom.match(fd.readline()) 

1395 if match is None: 

1396 break 

1397 number = int(match.group(1)) 

1398 pos = list(map(float, match.group(2, 3, 4))) 

1399 if number == -2: 

1400 pbc[npbc] = True 

1401 cell[npbc] = pos 

1402 npbc += 1 

1403 else: 

1404 numbers.append(max(number, 0)) 

1405 positions.append(pos) 

1406 atoms = Atoms(numbers, positions, pbc=pbc, cell=cell) 

1407 elif line.startswith('Energy=') or line.startswith('SCF Done:'): 

1408 # Some semi-empirical methods (Huckel, MINDO3, etc.), 

1409 # or SCF methods (HF, DFT, etc.) 

1410 energy = float(line.split('=')[1].split()[0].replace('D', 'e')) 

1411 energy *= Hartree 

1412 elif ( 

1413 line.startswith('E2 =') 

1414 or line.startswith('E3 =') 

1415 or line.startswith('E4(') 

1416 or line.startswith('DEMP5 =') 

1417 or line.startswith('E2(') 

1418 ): 

1419 # MP{2,3,4,5} energy 

1420 # also some double hybrid calculations, like B2PLYP 

1421 energy = float(line.split('=')[-1].strip().replace('D', 'e')) 

1422 energy *= Hartree 

1423 elif line.startswith('Wavefunction amplitudes converged. E(Corr)'): 

1424 # "correlated method" energy, e.g. CCSD 

1425 energy = float(line.split('=')[-1].strip().replace('D', 'e')) 

1426 energy *= Hartree 

1427 elif line.startswith('CCSD(T)='): 

1428 # CCSD(T) energy 

1429 energy = float(line.split('=')[-1].strip().replace('D', 'e')) 

1430 energy *= Hartree 

1431 elif ( 

1432 line.startswith('Mulliken charges') 

1433 or line.startswith('Lowdin Atomic Charges') 

1434 or line.startswith('Hirshfeld charges, spin densities,') 

1435 ): 

1436 # Löwdin is printed after Mulliken and overwrites `charges`. 

1437 # Hirshfeld is printed after Mulliken and overwrites `charges`. 

1438 results.update(_read_charges(fd)) 

1439 elif line.startswith('Dipole moment ') and energy is not None: 

1440 # dipole moment in `l601.exe`, printed unless `Pop=None` 

1441 # Skipped if energy is not printed in the same section. 

1442 # This happens in the last geometry record when `opt` or `irc` is 

1443 # specified. In this case, the record is compared with the previous 

1444 # one in `_compare_merge_configs`, and there the dipole moment 

1445 # from `l601` conflicts with the previous record from `l716`. 

1446 line = fd.readline().strip() 

1447 dipole = np.array([float(_) for _ in line.split()[1:6:2]]) * Debye 

1448 results['dipole'] = dipole 

1449 elif re.match(r'^Recovered energy=.*dipole=.*$', line): 

1450 # energy and dipole moment obtained from an external script 

1451 energy = float(line.split()[2].replace('D', 'e')) 

1452 energy *= Hartree 

1453 dipole = np.array([float(_) for _ in line.split()[4:7]]) * Debye 

1454 results['dipole'] = dipole 

1455 elif _re_l716.match(line): 

1456 # Sometimes Gaussian will print "Rotating derivatives to 

1457 # standard orientation" after the matched line (which looks like 

1458 # "(Enter /opt/gaussian/g16/l716.exe)", though the exact path 

1459 # depends on where Gaussian is installed). We *skip* the dipole 

1460 # in this case, because it might be rotated relative to the input 

1461 # orientation (and also it is numerically different even if the 

1462 # standard orientation is the same as the input orientation). 

1463 line = fd.readline().strip() 

1464 if not line.startswith('Dipole'): 

1465 continue 

1466 dip = line.split('=')[1].replace('D', 'e') 

1467 tokens = dip.split() 

1468 dipole = [] 

1469 # dipole elements can run together, depending on what method was 

1470 # used to calculate them. First see if there is a space between 

1471 # values. 

1472 if len(tokens) == 3: 

1473 dipole = list(map(float, tokens)) 

1474 elif len(dip) % 3 == 0: 

1475 # next, check if the number of tokens is divisible by 3 

1476 nchars = len(dip) // 3 

1477 for i in range(3): 

1478 dipole.append(float(dip[nchars * i : nchars * (i + 1)])) 

1479 else: 

1480 # otherwise, just give up on trying to parse it. 

1481 dipole = None 

1482 continue 

1483 # this dipole moment is printed in atomic units, e-Bohr 

1484 # ASE uses e-Angstrom for dipole moments. 

1485 results['dipole'] = np.array(dipole) * Bohr 

1486 elif _re_forceblock.match(line): 

1487 # skip 2 irrelevant lines 

1488 fd.readline() 

1489 fd.readline() 

1490 forces = [] 

1491 while True: 

1492 match = _re_atom.match(fd.readline()) 

1493 if match is None: 

1494 break 

1495 forces.append(list(map(float, match.group(2, 3, 4)))) 

1496 results['forces'] = np.array(forces) * Hartree / Bohr 

1497 if atoms is not None: 

1498 atoms.calc = SinglePointCalculator(atoms, energy=energy, **results) 

1499 _compare_merge_configs(configs, atoms) 

1500 return configs[index]