Coverage for ase/calculators/dftd3.py: 87.50%

272 statements  

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

1import os 

2import subprocess 

3from pathlib import Path 

4from warnings import warn 

5 

6import numpy as np 

7 

8from ase.calculators.calculator import ( 

9 BaseCalculator, 

10 Calculator, 

11 FileIOCalculator, 

12) 

13from ase.io import write 

14from ase.io.vasp import write_vasp 

15from ase.parallel import world 

16from ase.units import Bohr, Hartree 

17 

18 

19def dftd3_defaults(): 

20 default_parameters = { 

21 'xc': None, # PBE if no custom damping parameters 

22 'grad': True, # calculate forces/stress 

23 'abc': False, # ATM 3-body contribution 

24 'cutoff': 95 * Bohr, # Cutoff for 2-body calcs 

25 'cnthr': 40 * Bohr, # Cutoff for 3-body and CN calcs 

26 'old': False, # use old DFT-D2 method instead 

27 'damping': 'zero', # Default to zero-damping 

28 'tz': False, # 'triple zeta' alt. parameters 

29 's6': None, # damping parameters start here 

30 'sr6': None, 

31 's8': None, 

32 'sr8': None, 

33 'alpha6': None, 

34 'a1': None, 

35 'a2': None, 

36 'beta': None, 

37 } 

38 return default_parameters 

39 

40 

41class DFTD3(BaseCalculator): 

42 """Grimme DFT-D3 calculator""" 

43 

44 def __init__( 

45 self, 

46 label='ase_dftd3', # Label for dftd3 output files 

47 command=None, # Command for running dftd3 

48 dft=None, # DFT calculator 

49 comm=world, 

50 **kwargs, 

51 ): 

52 

53 # Convert from 'func' keyword to 'xc'. Internally, we only store 

54 # 'xc', but 'func' is also allowed since it is consistent with the 

55 # CLI dftd3 interface. 

56 func = kwargs.pop('func', None) 

57 if func is not None: 

58 if kwargs.get('xc') is not None: 

59 raise RuntimeError( 

60 'Both "func" and "xc" were provided! ' 

61 'Please provide at most one of these ' 

62 'two keywords. The preferred keyword ' 

63 'is "xc"; "func" is allowed for ' 

64 'consistency with the CLI dftd3 ' 

65 'interface.' 

66 ) 

67 kwargs['xc'] = func 

68 

69 # If the user did not supply an XC functional, but did attach a 

70 # DFT calculator that has XC set, then we will use that. Note that 

71 # DFTD3's spelling convention is different from most, so in general 

72 # you will have to explicitly set XC for both the DFT calculator and 

73 # for DFTD3 (and DFTD3's will likely be spelled differently...) 

74 if dft is not None and kwargs.get('xc') is None: 

75 dft_xc = dft.parameters.get('xc') 

76 if dft_xc is not None: 

77 kwargs['xc'] = dft_xc 

78 

79 dftd3 = PureDFTD3(label=label, command=command, comm=comm, **kwargs) 

80 

81 # dftd3 only implements energy, forces, and stresses (for periodic 

82 # systems). But, if a DFT calculator is attached, and that calculator 

83 # implements more properties, we expose those properties. 

84 # dftd3 contributions for those properties will be zero. 

85 if dft is None: 

86 self.implemented_properties = list(dftd3.dftd3_properties) 

87 else: 

88 self.implemented_properties = list(dft.implemented_properties) 

89 

90 # Should our arguments be "parameters" (passed to superclass) 

91 # or are they not really "parameters"? 

92 # 

93 # That's not really well defined. Let's not do anything then. 

94 super().__init__() 

95 

96 self.dftd3 = dftd3 

97 self.dft = dft 

98 

99 def todict(self): 

100 return {} 

101 

102 def calculate(self, atoms, properties, system_changes): 

103 common_props = set(self.dftd3.dftd3_properties) & set(properties) 

104 dftd3_results = self._get_properties(atoms, common_props, self.dftd3) 

105 

106 if self.dft is None: 

107 results = dftd3_results 

108 else: 

109 dft_results = self._get_properties(atoms, properties, self.dft) 

110 results = dict(dft_results) 

111 for name in set(results) & set(dftd3_results): 

112 assert np.shape(results[name]) == np.shape(dftd3_results[name]) 

113 results[name] += dftd3_results[name] 

114 

115 # Although DFTD3 may have calculated quantities not provided 

116 # by the calculator (e.g. stress), it would be wrong to 

117 # return those! Return only what corresponds to the DFT calc. 

118 assert set(results) == set(dft_results) 

119 self.results = results 

120 

121 def _get_properties(self, atoms, properties, calc): 

122 # We want any and all properties that the calculator 

123 # normally produces. So we intend to rob the calc.results 

124 # dictionary instead of only getting the requested properties. 

125 

126 import copy 

127 

128 for name in properties: 

129 calc.get_property(name, atoms) 

130 assert name in calc.results 

131 

132 # XXX maybe use get_properties() when that makes sense. 

133 results = copy.deepcopy(calc.results) 

134 assert set(properties) <= set(results) 

135 return results 

136 

137 

138class PureDFTD3(FileIOCalculator): 

139 """DFTD3 calculator without corresponding DFT contribution. 

140 

141 This class is an implementation detail.""" 

142 

143 name = 'puredftd3' 

144 

145 dftd3_properties = {'energy', 'free_energy', 'forces', 'stress'} 

146 implemented_properties = list(dftd3_properties) 

147 default_parameters = dftd3_defaults() 

148 damping_methods = {'zero', 'bj', 'zerom', 'bjm'} 

149 _legacy_default_command = 'dftd3' 

150 

151 def __init__( 

152 self, 

153 *, 

154 label='ase_dftd3', # Label for dftd3 output files 

155 command=None, # Command for running dftd3 

156 comm=world, 

157 **kwargs, 

158 ): 

159 

160 # FileIOCalculator would default to self.name to get the envvar 

161 # which determines the command. 

162 # We'll have to overrule that if we want to keep scripts working: 

163 command = command or self.cfg.get('ASE_DFTD3_COMMAND') 

164 

165 super().__init__(label=label, command=command, **kwargs) 

166 

167 # TARP: This is done because the calculator does not call 

168 # FileIOCalculator.calculate, but Calculator.calculate and does not 

169 # use the profile defined in FileIOCalculator.__init__ 

170 self.comm = comm 

171 

172 def set(self, **kwargs): 

173 changed_parameters = {} 

174 

175 # Check for unknown arguments. Don't raise an error, just let the 

176 # user know that we don't understand what they're asking for. 

177 unknown_kwargs = set(kwargs) - set(self.default_parameters) 

178 if unknown_kwargs: 

179 raise TypeError(f'Unknown keywords: {unknown_kwargs}') 

180 

181 changed_parameters.update(FileIOCalculator.set(self, **kwargs)) 

182 

183 # Ensure damping method is valid (zero, bj, zerom, bjm). 

184 damping = self.parameters['damping'] 

185 if damping is not None: 

186 damping = damping.lower() 

187 if damping not in self.damping_methods: 

188 raise ValueError(f'Unknown damping method {damping}!') 

189 

190 # d2 only is valid with 'zero' damping 

191 elif self.parameters['old'] and damping != 'zero': 

192 raise ValueError( 

193 'Only zero-damping can be used with the D2 ' 

194 'dispersion correction method!' 

195 ) 

196 

197 # If cnthr (cutoff for three-body and CN calculations) is greater 

198 # than cutoff (cutoff for two-body calculations), then set the former 

199 # equal to the latter, since that doesn't make any sense. 

200 if self.parameters['cnthr'] > self.parameters['cutoff']: 

201 warn( 

202 'WARNING: CN cutoff value of {cnthr} is larger than ' 

203 'regular cutoff value of {cutoff}! Reducing CN cutoff ' 

204 'to {cutoff}.' 

205 ''.format( 

206 cnthr=self.parameters['cnthr'], 

207 cutoff=self.parameters['cutoff'], 

208 ) 

209 ) 

210 self.parameters['cnthr'] = self.parameters['cutoff'] 

211 

212 # If you only care about the energy, gradient calculations (forces, 

213 # stresses) can be bypassed. This will greatly speed up calculations 

214 # in dense 3D-periodic systems with three-body corrections. But, we 

215 # can no longer say that we implement forces and stresses. 

216 # if not self.parameters['grad']: 

217 # for val in ['forces', 'stress']: 

218 # if val in self.implemented_properties: 

219 # self.implemented_properties.remove(val) 

220 

221 # Check to see if we're using custom damping parameters. 

222 zero_damppars = {'s6', 'sr6', 's8', 'sr8', 'alpha6'} 

223 bj_damppars = {'s6', 'a1', 's8', 'a2', 'alpha6'} 

224 zerom_damppars = {'s6', 'sr6', 's8', 'beta', 'alpha6'} 

225 all_damppars = zero_damppars | bj_damppars | zerom_damppars 

226 

227 self.custom_damp = False 

228 

229 damppars = set(kwargs) & all_damppars 

230 if damppars: 

231 self.custom_damp = True 

232 if damping == 'zero': 

233 valid_damppars = zero_damppars 

234 elif damping in ['bj', 'bjm']: 

235 valid_damppars = bj_damppars 

236 elif damping == 'zerom': 

237 valid_damppars = zerom_damppars 

238 

239 # If some but not all damping parameters are provided for the 

240 # selected damping method, raise an error. We don't have "default" 

241 # values for damping parameters, since those are stored in the 

242 # dftd3 executable & depend on XC functional. 

243 missing_damppars = valid_damppars - damppars 

244 if missing_damppars and missing_damppars != valid_damppars: 

245 raise ValueError( 

246 'An incomplete set of custom damping ' 

247 'parameters for the {} damping method was ' 

248 'provided! Expected: {}; got: {}' 

249 ''.format( 

250 damping, ', '.join(valid_damppars), ', '.join(damppars) 

251 ) 

252 ) 

253 

254 # If a user provides damping parameters that are not used in the 

255 # selected damping method, let them know that we're ignoring them. 

256 # If the user accidentally provided the *wrong* set of parameters, 

257 # (e.g., the BJ parameters when they are using zero damping), then 

258 # the previous check will raise an error, so we don't need to 

259 # worry about that here. 

260 if damppars - valid_damppars: 

261 warn( 

262 'WARNING: The following damping parameters are not ' 

263 'valid for the {} damping method and will be ignored: {}' 

264 ''.format(damping, ', '.join(damppars)) 

265 ) 

266 

267 # The default XC functional is PBE, but this is only set if the user 

268 # did not provide their own value for xc or any custom damping 

269 # parameters. 

270 if self.parameters['xc'] and self.custom_damp: 

271 warn( 

272 'WARNING: Custom damping parameters will be used ' 

273 'instead of those parameterized for {}!' 

274 ''.format(self.parameters['xc']) 

275 ) 

276 

277 if changed_parameters: 

278 self.results.clear() 

279 return changed_parameters 

280 

281 def calculate(self, atoms, properties, system_changes): 

282 # We don't call FileIOCalculator.calculate here, because that method 

283 # calls subprocess.call(..., shell=True), which we don't want to do. 

284 # So, we reproduce some content from that method here. 

285 Calculator.calculate(self, atoms, properties, system_changes) 

286 

287 # If a parameter file exists in the working directory, delete it 

288 # first. If we need that file, we'll recreate it later. 

289 localparfile = os.path.join(self.directory, '.dftd3par.local') 

290 if self.comm.rank == 0 and os.path.isfile(localparfile): 

291 os.remove(localparfile) 

292 

293 # Write XYZ or POSCAR file and .dftd3par.local file if we are using 

294 # custom damping parameters. 

295 self.write_input(self.atoms, properties, system_changes) 

296 # command = self._generate_command() 

297 

298 inputs = DFTD3Inputs( 

299 command=self.command, 

300 prefix=self.label, 

301 atoms=self.atoms, 

302 parameters=self.parameters, 

303 ) 

304 command = inputs.get_argv(custom_damp=self.custom_damp) 

305 

306 # Finally, call dftd3 and parse results. 

307 # DFTD3 does not run in parallel 

308 # so we only need it to run on 1 core 

309 errorcode = 0 

310 if self.comm.rank == 0: 

311 with open(self.label + '.out', 'w') as fd: 

312 errorcode = subprocess.call( 

313 command, cwd=self.directory, stdout=fd 

314 ) 

315 

316 errorcode = self.comm.sum_scalar(errorcode) 

317 

318 if errorcode: 

319 raise RuntimeError( 

320 '%s returned an error: %d' % (self.name, errorcode) 

321 ) 

322 

323 self.read_results() 

324 

325 def write_input(self, atoms, properties=None, system_changes=None): 

326 FileIOCalculator.write_input( 

327 self, atoms, properties=properties, system_changes=system_changes 

328 ) 

329 # dftd3 can either do fully 3D periodic or non-periodic calculations. 

330 # It cannot do calculations that are only periodic in 1 or 2 

331 # dimensions. If the atoms object is periodic in only 1 or 2 

332 # dimensions, then treat it as a fully 3D periodic system, but warn 

333 # the user. 

334 

335 if self.custom_damp: 

336 damppars = _get_damppars(self.parameters) 

337 else: 

338 damppars = None 

339 

340 if self.comm.rank == 0: 

341 self._actually_write_input( 

342 directory=Path(self.directory), 

343 atoms=atoms, 

344 properties=properties, 

345 prefix=self.label, 

346 damppars=damppars, 

347 pbc=any(atoms.pbc), 

348 ) 

349 

350 def _actually_write_input( 

351 self, directory, prefix, atoms, properties, damppars, pbc: bool 

352 ): 

353 if pbc: 

354 fname = directory / f'{prefix}.POSCAR' 

355 # We sort the atoms so that the atomtypes list becomes as 

356 # short as possible. The dftd3 program can only handle 10 

357 # atomtypes 

358 write_vasp(fname, atoms, sort=True) 

359 else: 

360 fname = directory / f'{prefix}.xyz' 

361 write(fname, atoms, format='xyz', parallel=False) 

362 

363 # Generate custom damping parameters file. This is kind of ugly, but 

364 # I don't know of a better way of doing this. 

365 if damppars is not None: 

366 damp_fname = directory / '.dftd3par.local' 

367 with open(damp_fname, 'w') as fd: 

368 fd.write(' '.join(damppars)) 

369 

370 def _outname(self): 

371 return Path(self.directory) / f'{self.label}.out' 

372 

373 def _read_and_broadcast_results(self): 

374 from ase.parallel import broadcast 

375 

376 if self.comm.rank == 0: 

377 output = DFTD3Output( 

378 directory=self.directory, stdout_path=self._outname() 

379 ) 

380 dct = output.read( 

381 atoms=self.atoms, read_forces=bool(self.parameters['grad']) 

382 ) 

383 else: 

384 dct = None 

385 

386 dct = broadcast(dct, root=0, comm=self.comm) 

387 return dct 

388 

389 def read_results(self): 

390 results = self._read_and_broadcast_results() 

391 self.results = results 

392 

393 

394class DFTD3Inputs: 

395 dftd3_flags = {'grad', 'pbc', 'abc', 'old', 'tz'} 

396 

397 def __init__(self, command, prefix, atoms, parameters): 

398 self.command = command 

399 self.prefix = prefix 

400 self.atoms = atoms 

401 self.parameters = parameters 

402 

403 @property 

404 def pbc(self): 

405 return any(self.atoms.pbc) 

406 

407 @property 

408 def inputformat(self): 

409 if self.pbc: 

410 return 'POSCAR' 

411 else: 

412 return 'xyz' 

413 

414 def get_argv(self, custom_damp): 

415 argv = self.command.split() 

416 

417 argv.append(f'{self.prefix}.{self.inputformat}') 

418 

419 if not custom_damp: 

420 xc = self.parameters.get('xc') 

421 if xc is None: 

422 xc = 'pbe' 

423 argv += ['-func', xc.lower()] 

424 

425 for arg in self.dftd3_flags: 

426 if self.parameters.get(arg): 

427 argv.append('-' + arg) 

428 

429 if self.pbc: 

430 argv.append('-pbc') 

431 

432 argv += ['-cnthr', str(self.parameters['cnthr'] / Bohr)] 

433 argv += ['-cutoff', str(self.parameters['cutoff'] / Bohr)] 

434 

435 if not self.parameters['old']: 

436 argv.append('-' + self.parameters['damping']) 

437 

438 return argv 

439 

440 

441class DFTD3Output: 

442 def __init__(self, directory, stdout_path): 

443 self.directory = Path(directory) 

444 self.stdout_path = Path(stdout_path) 

445 

446 def read(self, *, atoms, read_forces): 

447 results = {} 

448 

449 energy = self.read_energy() 

450 results['energy'] = energy 

451 results['free_energy'] = energy 

452 

453 if read_forces: 

454 results['forces'] = self.read_forces(atoms) 

455 

456 if any(atoms.pbc): 

457 results['stress'] = self.read_stress(atoms.cell) 

458 

459 return results 

460 

461 def read_forces(self, atoms): 

462 forcename = self.directory / 'dftd3_gradient' 

463 with open(forcename) as fd: 

464 forces = self.parse_forces(fd) 

465 

466 assert len(forces) == len(atoms) 

467 

468 forces *= -Hartree / Bohr 

469 # XXXX ordering! 

470 if any(atoms.pbc): 

471 # This seems to be due to vasp file sorting. 

472 # If that sorting rule changes, we will get garbled 

473 # forces! 

474 ind = np.argsort(atoms.symbols) 

475 forces[ind] = forces.copy() 

476 return forces 

477 

478 def read_stress(self, cell): 

479 volume = cell.volume 

480 assert volume > 0 

481 

482 stress = self.read_cellgradient() 

483 stress *= Hartree / Bohr / volume 

484 stress = stress.T @ cell 

485 return stress.flat[[0, 4, 8, 5, 2, 1]] 

486 

487 def read_cellgradient(self): 

488 with (self.directory / 'dftd3_cellgradient').open() as fd: 

489 return self.parse_cellgradient(fd) 

490 

491 def read_energy(self) -> float: 

492 with self.stdout_path.open() as fd: 

493 return self.parse_energy(fd, self.stdout_path) 

494 

495 def parse_energy(self, fd, outname): 

496 for line in fd: 

497 if line.startswith(' program stopped'): 

498 if 'functional name unknown' in line: 

499 message = ( 

500 'Unknown DFTD3 functional name. ' 

501 'Please check the dftd3.f source file ' 

502 'for the list of known functionals ' 

503 'and their spelling.' 

504 ) 

505 else: 

506 message = ( 

507 'dftd3 failed! Please check the {} ' 

508 'output file and report any errors ' 

509 'to the ASE developers.' 

510 ''.format(outname) 

511 ) 

512 raise RuntimeError(message) 

513 

514 if line.startswith(' Edisp'): 

515 # line looks something like this: 

516 # 

517 # Edisp /kcal,au,ev: xxx xxx xxx 

518 # 

519 parts = line.split() 

520 assert parts[1][0] == '/' 

521 index = 2 + parts[1][1:-1].split(',').index('au') 

522 e_dftd3 = float(parts[index]) * Hartree 

523 return e_dftd3 

524 

525 raise RuntimeError( 

526 'Could not parse energy from dftd3 output, see file {}'.format( 

527 outname 

528 ) 

529 ) 

530 

531 def parse_forces(self, fd): 

532 forces = [] 

533 for i, line in enumerate(fd): 

534 forces.append(line.split()) 

535 return np.array(forces, dtype=float) 

536 

537 def parse_cellgradient(self, fd): 

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

539 for i, line in enumerate(fd): 

540 for j, x in enumerate(line.split()): 

541 stress[i, j] = float(x) 

542 # Check if all stress elements are present? 

543 # Check if file is longer? 

544 return stress 

545 

546 

547def _get_damppars(par): 

548 damping = par['damping'] 

549 

550 damppars = [] 

551 

552 # s6 is always first 

553 damppars.append(str(float(par['s6']))) 

554 

555 # sr6 is the second value for zero{,m} damping, a1 for bj{,m} 

556 if damping in ['zero', 'zerom']: 

557 damppars.append(str(float(par['sr6']))) 

558 elif damping in ['bj', 'bjm']: 

559 damppars.append(str(float(par['a1']))) 

560 

561 # s8 is always third 

562 damppars.append(str(float(par['s8']))) 

563 

564 # sr8 is fourth for zero, a2 for bj{,m}, beta for zerom 

565 if damping == 'zero': 

566 damppars.append(str(float(par['sr8']))) 

567 elif damping in ['bj', 'bjm']: 

568 damppars.append(str(float(par['a2']))) 

569 elif damping == 'zerom': 

570 damppars.append(str(float(par['beta']))) 

571 # alpha6 is always fifth 

572 damppars.append(str(int(par['alpha6']))) 

573 

574 # last is the version number 

575 if par['old']: 

576 damppars.append('2') 

577 elif damping == 'zero': 

578 damppars.append('3') 

579 elif damping == 'bj': 

580 damppars.append('4') 

581 elif damping == 'zerom': 

582 damppars.append('5') 

583 elif damping == 'bjm': 

584 damppars.append('6') 

585 return damppars