Coverage for ase/io/nwchem/nwwriter.py: 78.80%

283 statements  

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

1import os 

2import random 

3import string 

4import warnings 

5from copy import deepcopy 

6 

7import numpy as np 

8 

9from ase.calculators.calculator import KPoints, kpts2kpts 

10 

11_special_kws = [ 

12 'center', 

13 'autosym', 

14 'autoz', 

15 'theory', 

16 'basis', 

17 'xc', 

18 'task', 

19 'set', 

20 'symmetry', 

21 'label', 

22 'geompar', 

23 'basispar', 

24 'kpts', 

25 'bandpath', 

26 'restart_kw', 

27 'pretasks', 

28 'charge', 

29] 

30 

31_system_type = {1: 'polymer', 2: 'surface', 3: 'crystal'} 

32 

33 

34def _render_geom(atoms, params: dict) -> list[str]: 

35 """Generate the geometry block 

36 

37 Parameters 

38 ---------- 

39 atoms : Atoms 

40 Geometry for the computation 

41 params : dict 

42 Parameter set for the computation 

43 

44 Returns 

45 ------- 

46 geom : [str] 

47 Geometry block to use in the computation 

48 """ 

49 geom_header = ['geometry units angstrom'] 

50 for geomkw in ['center', 'autosym', 'autoz']: 

51 geom_header.append(geomkw if params.get(geomkw) else 'no' + geomkw) 

52 if 'geompar' in params: 

53 geom_header.append(params['geompar']) 

54 geom = [' '.join(geom_header)] 

55 

56 outpos = atoms.get_positions() 

57 pbc = atoms.pbc 

58 if np.any(pbc): 

59 scpos = atoms.get_scaled_positions() 

60 for i, pbci in enumerate(pbc): 

61 if pbci: 

62 outpos[:, i] = scpos[:, i] 

63 npbc = pbc.sum() 

64 cellpars = atoms.cell.cellpar() 

65 geom.append(f' system {_system_type[npbc]} units angstrom') 

66 if npbc == 3: 

67 geom.append(' lattice_vectors') 

68 for row in atoms.cell: 

69 geom.append(' {:20.16e} {:20.16e} {:20.16e}'.format(*row)) 

70 else: 

71 if pbc[0]: 

72 geom.append(f' lat_a {cellpars[0]:20.16e}') 

73 if pbc[1]: 

74 geom.append(f' lat_b {cellpars[1]:20.16e}') 

75 if pbc[2]: 

76 geom.append(f' lat_c {cellpars[2]:20.16e}') 

77 if pbc[1] and pbc[2]: 

78 geom.append(f' alpha {cellpars[3]:20.16e}') 

79 if pbc[0] and pbc[2]: 

80 geom.append(f' beta {cellpars[4]:20.16e}') 

81 if pbc[1] and pbc[0]: 

82 geom.append(f' gamma {cellpars[5]:20.16e}') 

83 geom.append(' end') 

84 

85 for i, atom in enumerate(atoms): 

86 geom.append( 

87 ' {:<2} {:20.16e} {:20.16e} {:20.16e}'.format( 

88 atom.symbol, *outpos[i] 

89 ) 

90 ) 

91 symm = params.get('symmetry') 

92 if symm is not None: 

93 geom.append(f' symmetry {symm}') 

94 geom.append('end') 

95 return geom 

96 

97 

98def _render_basis(theory, params: dict) -> list[str]: 

99 """Infer the basis set block 

100 

101 Arguments 

102 --------- 

103 theory : str 

104 Name of the theory used for the calculation 

105 params : dict 

106 Parameters for the computation 

107 

108 Returns 

109 ------- 

110 [str] 

111 List of input file lines for the basis block 

112 """ 

113 

114 # Break if no basis set is provided and non is applicable 

115 if 'basis' not in params: 

116 if theory in ['pspw', 'band', 'paw']: 

117 return [] 

118 

119 # Write the header section 

120 if 'basispar' in params: 

121 header = 'basis {} noprint'.format(params['basispar']) 

122 else: 

123 header = 'basis noprint' 

124 basis_out = [header] 

125 

126 # Write the basis set for each atom type 

127 basis_in = params.get('basis', '3-21G') 

128 if isinstance(basis_in, str): 

129 basis_out.append(f' * library {basis_in}') 

130 else: 

131 for symbol, ibasis in basis_in.items(): 

132 basis_out.append(f'{symbol:>4} library {ibasis}') 

133 basis_out.append('end') 

134 return basis_out 

135 

136 

137_special_keypairs = [ 

138 ('nwpw', 'simulation_cell'), 

139 ('nwpw', 'carr-parinello'), 

140 ('nwpw', 'brillouin_zone'), 

141 ('tddft', 'grad'), 

142] 

143 

144 

145def _render_brillouin_zone(array, name=None) -> list[str]: 

146 out = [' brillouin_zone'] 

147 if name is not None: 

148 out += [f' zone_name {name}'] 

149 template = ' kvector' + ' {:20.16e}' * array.shape[1] 

150 for row in array: 

151 out.append(template.format(*row)) 

152 out.append(' end') 

153 return out 

154 

155 

156def _render_bandpath(bp) -> list[str]: 

157 if bp is None: 

158 return [] 

159 out = ['nwpw'] 

160 out += _render_brillouin_zone(bp.kpts, name=bp.path) 

161 out += [f' zone_structure_name {bp.path}', 'end', 'task band structure'] 

162 return out 

163 

164 

165def _format_line(key, val) -> str: 

166 if val is None: 

167 return key 

168 if isinstance(val, bool): 

169 return f'{key} .{str(val).lower()}.' 

170 else: 

171 return ' '.join([key, str(val)]) 

172 

173 

174def _format_block(key, val, nindent=0) -> list[str]: 

175 prefix = ' ' * nindent 

176 prefix2 = ' ' * (nindent + 1) 

177 if val is None: 

178 return [prefix + key] 

179 

180 if not isinstance(val, dict): 

181 return [prefix + _format_line(key, val)] 

182 

183 out = [prefix + key] 

184 for subkey, subval in val.items(): 

185 if (key, subkey) in _special_keypairs: 

186 if (key, subkey) == ('nwpw', 'brillouin_zone'): 

187 out += _render_brillouin_zone(subval) 

188 else: 

189 out += _format_block(subkey, subval, nindent + 1) 

190 else: 

191 if isinstance(subval, dict): 

192 subval = ' '.join( 

193 [_format_line(a, b) for a, b in subval.items()] 

194 ) 

195 out.append(prefix2 + ' '.join([_format_line(subkey, subval)])) 

196 out.append(prefix + 'end') 

197 return out 

198 

199 

200def _render_other(params) -> list[str]: 

201 """Render other commands 

202 

203 Parameters 

204 ---------- 

205 params : dict 

206 Parameter set to be rendered 

207 

208 Returns 

209 ------- 

210 out : [str] 

211 Block defining other commands 

212 """ 

213 out = [] 

214 for kw, block in params.items(): 

215 if kw in _special_kws: 

216 continue 

217 out += _format_block(kw, block) 

218 return out 

219 

220 

221def _render_set(set_params) -> list[str]: 

222 """Render the commands for the set parameters 

223 

224 Parameters 

225 ---------- 

226 set_params : dict 

227 Parameters being set 

228 

229 Returns 

230 ------- 

231 out : [str] 

232 Block defining set commands 

233 """ 

234 return ['set ' + _format_line(key, val) for key, val in set_params.items()] 

235 

236 

237_gto_theories = [ 

238 'tce', 

239 'ccsd', 

240 'tddft', 

241 'scf', 

242 'dft', 

243 'direct_mp2', 

244 'mp2', 

245 'rimp2', 

246] 

247_pw_theories = ['band', 'pspw', 'paw'] 

248_all_theories = _gto_theories + _pw_theories 

249 

250 

251def _get_theory(params: dict) -> str: 

252 """Infer the theory given the user-provided settings 

253 

254 Parameters 

255 ---------- 

256 params : dict 

257 Parameters for the computation 

258 

259 Returns 

260 ------- 

261 theory : str 

262 Theory directive to use 

263 """ 

264 # Default: user-provided theory 

265 theory = params.get('theory') 

266 if theory is not None: 

267 return theory 

268 

269 # Check if the user passed a theory to xc 

270 xc = params.get('xc') 

271 if xc in _all_theories: 

272 return xc 

273 

274 # Check for input blocks that correspond to a particular level of 

275 # theory. Correlated theories (e.g. CCSD) are checked first. 

276 for kw in _gto_theories: 

277 if kw in params: 

278 return kw 

279 

280 # If the user passed an 'nwpw' block, then they want a plane-wave 

281 # calculation, but what kind? If they request k-points, then 

282 # they want 'band', otherwise assume 'pspw' (if the user wants 

283 # to use 'paw', they will have to ask for it specifically). 

284 nwpw = params.get('nwpw') 

285 if nwpw is not None: 

286 if 'monkhorst-pack' in nwpw or 'brillouin_zone' in nwpw: 

287 return 'band' 

288 return 'pspw' 

289 

290 # When all else fails, default to dft. 

291 return 'dft' 

292 

293 

294_xc_conv = dict( 

295 lda='slater pw91lda', 

296 pbe='xpbe96 cpbe96', 

297 revpbe='revpbe cpbe96', 

298 rpbe='rpbe cpbe96', 

299 pw91='xperdew91 perdew91', 

300) 

301 

302 

303def _update_mult(magmom_tot: int, params: dict) -> None: 

304 """Update parameters for multiplicity given the magnetic moment 

305 

306 For example, sets the number of open shells for SCF calculations 

307 and the multiplicity for DFT calculations. 

308 

309 Parameters 

310 ---------- 

311 magmom_tot : int 

312 Total magnetic moment of the system 

313 params : dict 

314 Current set of parameters, will be modified 

315 """ 

316 # Determine theory and multiplicity 

317 theory = params['theory'] 

318 if magmom_tot == 0: 

319 magmom_mult = 1 

320 else: 

321 magmom_mult = np.sign(magmom_tot) * (abs(magmom_tot) + 1) 

322 

323 # Adjust the kwargs for each type of theory 

324 if 'scf' in params: 

325 for kw in [ 

326 'nopen', 

327 'singlet', 

328 'doublet', 

329 'triplet', 

330 'quartet', 

331 'quintet', 

332 'sextet', 

333 'septet', 

334 'octet', 

335 ]: 

336 if kw in params['scf']: 

337 break 

338 else: 

339 params['scf']['nopen'] = magmom_tot 

340 elif theory in ['scf', 'mp2', 'direct_mp2', 'rimp2', 'ccsd', 'tce']: 

341 params['scf'] = dict(nopen=magmom_tot) 

342 

343 if 'dft' in params: 

344 if 'mult' not in params['dft']: 

345 params['dft']['mult'] = magmom_mult 

346 elif theory in ['dft', 'tddft']: 

347 params['dft'] = dict(mult=magmom_mult) 

348 

349 if 'nwpw' in params: 

350 if 'mult' not in params['nwpw']: 

351 params['nwpw']['mult'] = magmom_mult 

352 elif theory in ['pspw', 'band', 'paw']: 

353 params['nwpw'] = dict(mult=magmom_mult) 

354 

355 

356def _update_kpts(atoms, params) -> None: 

357 """Converts top-level 'kpts' argument to native keywords 

358 

359 Parameters 

360 ---------- 

361 atoms : Atoms 

362 Input structure 

363 params : dict 

364 Current parameter set, will be updated 

365 """ 

366 kpts = params.get('kpts') 

367 if kpts is None: 

368 return 

369 

370 nwpw = params.get('nwpw', {}) 

371 

372 if 'monkhorst-pack' in nwpw or 'brillouin_zone' in nwpw: 

373 raise ValueError('Redundant k-points specified!') 

374 

375 if isinstance(kpts, KPoints): 

376 nwpw['brillouin_zone'] = kpts.kpts 

377 elif isinstance(kpts, dict): 

378 if kpts.get('gamma', False) or 'size' not in kpts: 

379 nwpw['brillouin_zone'] = kpts2kpts(kpts, atoms).kpts 

380 else: 

381 nwpw['monkhorst-pack'] = ' '.join(map(str, kpts['size'])) 

382 elif isinstance(kpts, np.ndarray): 

383 nwpw['brillouin_zone'] = kpts 

384 else: 

385 nwpw['monkhorst-pack'] = ' '.join(map(str, kpts)) 

386 

387 params['nwpw'] = nwpw 

388 

389 

390def _render_pretask( 

391 this_step: dict, 

392 previous_basis: list[str] | None, 

393 wfc_path: str, 

394 next_steps: list[dict], 

395) -> tuple[list[str], list[str]]: 

396 """Generate input file lines that perform a cheaper method first 

397 

398 Parameters 

399 ---------- 

400 this_step: dict 

401 Input parameters used to define the computation 

402 previous_basis: [str], optional 

403 Basis set block used in the previous step 

404 wfc_path: str 

405 Name of the wavefunction path 

406 next_steps: [dict] 

407 Parameters for the next steps in the calculation. 

408 This function will adjust the next steps to read 

409 and project from the wave functions written to disk by this step 

410 if the basis set changes between this step and the next. 

411 

412 Returns 

413 ------- 

414 output: [str] 

415 Output lines for this task 

416 this_basis: [str] 

417 Basis set block used for this task 

418 """ 

419 

420 # Get the theory for the next step 

421 next_step = next_steps[0] 

422 next_theory = _get_theory(next_step) 

423 next_step['theory'] = next_theory 

424 out = [] 

425 if next_theory not in ['dft', 'mp2', 'direct_mp2', 'rimp2', 'scf']: 

426 raise ValueError(f'Initial guesses not supported for {next_theory}') 

427 

428 # Determine the theory for this step 

429 this_theory = _get_theory(this_step) 

430 this_step['theory'] = this_theory 

431 if this_theory not in ['dft', 'scf']: 

432 raise ValueError('Initial guesses must use either dft or scf') 

433 

434 # Determine which basis set to use for this step. Our priorities 

435 # 1. Basis defined explicitly in this step 

436 # 2. Basis set of the previous step 

437 # 3. Basis set of the target computation level 

438 if 'basis' in this_step: 

439 this_basis = _render_basis(this_theory, this_step) 

440 elif previous_basis is not None: 

441 this_basis = previous_basis.copy() 

442 else: 

443 # Use the basis for the last step 

444 this_basis = _render_basis(next_theory, next_steps[-1]) 

445 

446 # Determine the basis for the next step 

447 # If not defined, it'll be the same as this step 

448 if 'basis' in next_step: 

449 next_basis = _render_basis(next_theory, next_step) 

450 else: 

451 next_basis = this_basis 

452 

453 # Set up projections if needed 

454 if this_basis == next_basis: 

455 out.append('\n'.join(this_basis)) 

456 proj_from = None # We do not need to project basis 

457 else: 

458 # Check for known limitations of NWChem 

459 if this_theory != next_theory: 

460 msg = ( 

461 'Theories must be the same if basis are different. ' 

462 f'This step: {this_theory}//{this_basis} ' 

463 f'Next step: {next_theory}//{next_basis}' 

464 ) 

465 if 'basis' not in this_step: 

466 msg += f'. Consider specifying basis in {this_step}' 

467 raise ValueError(msg) 

468 if not any('* library' in x for x in this_basis): 

469 raise ValueError( 

470 'We can only support projecting from systems ' 

471 'where all atoms share the same basis' 

472 ) 

473 

474 # Append a new name to this basis function by 

475 # appending it as the first argument of the basis block 

476 proj_from = f'smb_{len(next_steps)}' 

477 this_basis[0] = f'basis {proj_from} {this_basis[0][6:]}' 

478 out.append('\n'.join(this_basis)) 

479 

480 # Point ao basis (the active basis set) to this new basis set 

481 out.append(f'set "ao basis" {proj_from}') 

482 

483 # Insert a command to write wfcs from this computation to disk 

484 if this_theory not in this_step: 

485 this_step[this_theory] = {} 

486 if 'vectors' not in this_step[this_theory]: 

487 this_step[this_theory]['vectors'] = {} 

488 this_step[this_theory]['vectors']['output'] = wfc_path 

489 

490 # Check if the initial theory changes 

491 if this_theory != next_theory and 'lindep:n_dep' not in this_step.get( 

492 'set', {} 

493 ): 

494 warnings.warn( 

495 'Loading initial guess may fail if you do not specify' 

496 ' the number of linearly-dependent basis functions.' 

497 ' Consider adding {"set": {"lindep:n_dep": 0}} ' 

498 f' to the step: {this_step}.' 

499 ) 

500 

501 # Add this to the input file along with a "task * ignore" command 

502 out.extend( 

503 [ 

504 '\n'.join(_render_other(this_step)), 

505 '\n'.join(_render_set(this_step.get('set', {}))), 

506 f'task {this_theory} ignore', 

507 ] 

508 ) 

509 

510 # Command to read the wavefunctions in the next step 

511 # Theory used to get the wavefunctions may be different (mp2 uses SCF) 

512 wfc_theory = 'scf' if 'mp2' in next_theory else next_theory 

513 next_step = next_step 

514 if wfc_theory not in next_step: 

515 next_step[wfc_theory] = {} 

516 if 'vectors' not in next_step[wfc_theory]: 

517 next_step[wfc_theory]['vectors'] = {} 

518 

519 if proj_from is None: 

520 # No need for projection 

521 next_step[wfc_theory]['vectors']['input'] = wfc_path 

522 else: 

523 # Define that we should project from our basis set 

524 next_step[wfc_theory]['vectors']['input'] = ( 

525 f'project {proj_from} {wfc_path}' 

526 ) 

527 

528 # Replace the name of the basis set to the default 

529 out.append('set "ao basis" "ao basis"') 

530 

531 return out, this_basis 

532 

533 

534def write_nwchem_in(fd, atoms, properties=None, echo=False, **params): 

535 """Writes NWChem input file. 

536 

537 See :class:`~ase.calculators.nwchem.NWChem` for available params. 

538 

539 Parameters 

540 ---------- 

541 fd 

542 file descriptor 

543 atoms 

544 atomic configuration 

545 properties 

546 list of properties to compute; by default only the 

547 calculation of the energy is requested 

548 echo 

549 if True include the `echo` keyword at the top of the file, 

550 which causes the content of the input file to be included 

551 in the output file 

552 params 

553 dict of instructions blocks to be included 

554 """ 

555 # Copy so we can alter params w/o changing it for the function caller 

556 params = deepcopy(params) 

557 

558 if properties is None: 

559 properties = ['energy'] 

560 

561 if 'stress' in properties: 

562 if 'set' not in params: 

563 params['set'] = {} 

564 params['set']['includestress'] = True 

565 

566 task = params.get('task') 

567 if task is None: 

568 if 'stress' in properties or 'forces' in properties: 

569 task = 'gradient' 

570 else: 

571 task = 'energy' 

572 

573 _update_kpts(atoms, params) 

574 

575 # Determine the theory for each step 

576 # We determine the theory ahead of time because it is 

577 # used when generating other parts of the input file (e.g., _get_mult) 

578 theory = _get_theory(params) 

579 params['theory'] = theory 

580 

581 for pretask in params.get('pretasks', []): 

582 pretask['theory'] = _get_theory(pretask) 

583 

584 if 'xc' in params: 

585 xc = _xc_conv.get(params['xc'].lower(), params['xc']) 

586 if theory in ['dft', 'tddft']: 

587 if 'dft' not in params: 

588 params['dft'] = {} 

589 params['dft']['xc'] = xc 

590 elif theory in ['pspw', 'band', 'paw']: 

591 if 'nwpw' not in params: 

592 params['nwpw'] = {} 

593 params['nwpw']['xc'] = xc 

594 

595 # Update the multiplicity given the charge of the system 

596 magmom_tot = int(atoms.get_initial_magnetic_moments().sum()) 

597 _update_mult(magmom_tot, params) 

598 for pretask in params.get('pretasks', []): 

599 _update_mult(magmom_tot, pretask) 

600 

601 # Determine the header options 

602 label = params.get('label', 'nwchem') 

603 perm = os.path.abspath(params.pop('perm', label)) 

604 scratch = os.path.abspath(params.pop('scratch', label)) 

605 restart_kw = params.get('restart_kw', 'start') 

606 if restart_kw not in ('start', 'restart'): 

607 raise ValueError('Unrecognised restart keyword: {}!'.format(restart_kw)) 

608 short_label = label.rsplit('/', 1)[-1] 

609 if echo: 

610 out = ['echo'] 

611 else: 

612 out = [] 

613 

614 # Defines the geometry and global options 

615 out.extend( 

616 [ 

617 f'title "{short_label}"', 

618 f'permanent_dir {perm}', 

619 f'scratch_dir {scratch}', 

620 f'{restart_kw} {short_label}', 

621 '\n'.join(_render_set(params.get('set', {}))), 

622 '\n'.join(_render_geom(atoms, params)), 

623 ] 

624 ) 

625 

626 # Add the charge if provided 

627 if 'charge' in params: 

628 out.append(f'charge {params["charge"]}') 

629 

630 # Define the memory separately from the other options so that it 

631 # is defined before any initial wfc guesses are performed 

632 memory_opts = params.pop('memory', None) 

633 if memory_opts is not None: 

634 out.extend(_render_other(dict(memory=memory_opts))) 

635 

636 # If desired, output commands to generate the initial wavefunctions 

637 if 'pretasks' in params: 

638 wfc_path = f'tmp-{"".join(random.choices(string.hexdigits, k=8))}.wfc' 

639 pretasks = params['pretasks'] 

640 previous_basis = None 

641 for this_ind, this_step in enumerate(pretasks): 

642 new_out, previous_basis = _render_pretask( 

643 this_step, 

644 previous_basis, 

645 wfc_path, 

646 pretasks[this_ind + 1 :] + [params], 

647 ) 

648 out.extend(new_out) 

649 

650 # Finish output file with the commands to perform the desired computation 

651 out.extend( 

652 [ 

653 '\n'.join(_render_basis(theory, params)), 

654 '\n'.join(_render_other(params)), 

655 f'task {theory} {task}', 

656 '\n'.join(_render_bandpath(params.get('bandpath', None))), 

657 ] 

658 ) 

659 

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