Coverage for ase/calculators/dftb.py: 75.74%
338 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""This module defines a FileIOCalculator for DFTB+
3https://www.dftbplus.org/
4https://www.dftb.org/
6Initial development: markus.kaukonen@iki.fi
7"""
9import os
11import numpy as np
13from ase.calculators.calculator import (
14 BadConfiguration,
15 FileIOCalculator,
16 kpts2ndarray,
17 kpts2sizeandoffsets,
18)
19from ase.units import Bohr, Hartree
22class Dftb(FileIOCalculator):
23 implemented_properties = ['energy', 'forces', 'charges', 'stress', 'dipole']
24 discard_results_on_any_change = True
26 fileio_rules = FileIOCalculator.ruleset(
27 configspec=dict(skt_path=None), stdout_name='{prefix}.out'
28 )
30 def __init__(
31 self,
32 restart=None,
33 ignore_bad_restart_file=FileIOCalculator._deprecated,
34 label='dftb',
35 atoms=None,
36 kpts=None,
37 slako_dir=None,
38 command=None,
39 profile=None,
40 with_tags=False,
41 **kwargs,
42 ):
43 """
44 All keywords for the dftb_in.hsd input file (see the DFTB+ manual)
45 can be set by ASE. Consider the following input file block::
47 Hamiltonian = DFTB {
48 SCC = Yes
49 SCCTolerance = 1e-8
50 MaxAngularMomentum = {
51 H = s
52 O = p
53 }
54 }
56 This can be generated by the DFTB+ calculator by using the
57 following settings:
59 >>> from ase.calculators.dftb import Dftb
60 >>>
61 >>> calc = Dftb(Hamiltonian_='DFTB', # line is included by default
62 ... Hamiltonian_SCC='Yes',
63 ... Hamiltonian_SCCTolerance=1e-8,
64 ... Hamiltonian_MaxAngularMomentum_='',
65 ... Hamiltonian_MaxAngularMomentum_H='s',
66 ... Hamiltonian_MaxAngularMomentum_O='p')
68 In addition to keywords specific to DFTB+, also the following keywords
69 arguments can be used:
71 restart: str
72 Prefix for restart file. May contain a directory.
73 Default is None: don't restart.
74 ignore_bad_restart_file: bool
75 Ignore broken or missing restart file. By default, it is an
76 error if the restart file is missing or broken.
77 label: str (default 'dftb')
78 Prefix used for the main output file (<label>.out).
79 atoms: Atoms object (default None)
80 Optional Atoms object to which the calculator will be
81 attached. When restarting, atoms will get its positions and
82 unit-cell updated from file.
83 kpts: (default None)
84 Brillouin zone sampling:
86 * ``(1,1,1)`` or ``None``: Gamma-point only
87 * ``(n1,n2,n3)``: Monkhorst-Pack grid
88 * ``dict``: Interpreted as a path in the Brillouin zone if
89 it contains the 'path_' keyword. Otherwise it is converted
90 into a Monkhorst-Pack grid using
91 ``ase.calculators.calculator.kpts2sizeandoffsets``
92 * ``[(k11,k12,k13),(k21,k22,k23),...]``: Explicit (Nkpts x 3)
93 array of k-points in units of the reciprocal lattice vectors
94 (each with equal weight)
95 with_tags: bool (default False)
96 Whether to use atom tags to distinguish between different chemical
97 species. When enabled, atoms with different tags are treated as
98 distinct species, even if they have the same chemical symbol.
99 For example, hydrogen atoms in a nanoparticle (tag 1) and hydrogen
100 atoms in a solvent (tag 2) would be represented as "H1" and "H2",
101 requiring separate Slater-Koster files: "H1-H1.skf", "H1-H2.skf",
102 and "H2-H2.skf".
104 Additional attribute to be set by the embed() method:
106 pcpot: PointCharge object
107 An external point charge potential (for QM/MM calculations)
108 """
110 if command is None:
111 if 'DFTB_COMMAND' in self.cfg:
112 command = self.cfg['DFTB_COMMAND'] + ' > PREFIX.out'
114 if command is None and profile is None:
115 try:
116 profile = self.load_argv_profile(self.cfg, 'dftb')
117 except BadConfiguration:
118 pass
120 if command is None:
121 command = 'dftb+ > PREFIX.out'
123 if slako_dir is None:
124 if profile is not None:
125 slako_dir = profile.configvars.get('skt_path')
127 if slako_dir is None:
128 slako_dir = self.cfg.get('DFTB_PREFIX', './')
129 if not slako_dir.endswith('/'):
130 slako_dir += '/'
132 self.slako_dir = slako_dir
133 if kwargs.get('Hamiltonian_', 'DFTB') == 'DFTB':
134 self.default_parameters = dict(
135 Hamiltonian_='DFTB',
136 Hamiltonian_SlaterKosterFiles_='Type2FileNames',
137 Hamiltonian_SlaterKosterFiles_Prefix=self.slako_dir,
138 Hamiltonian_SlaterKosterFiles_Separator='"-"',
139 Hamiltonian_SlaterKosterFiles_Suffix='".skf"',
140 Hamiltonian_MaxAngularMomentum_='',
141 Options_='',
142 Options_WriteResultsTag='Yes',
143 ParserOptions_='',
144 ParserOptions_ParserVersion=1,
145 ParserOptions_IgnoreUnprocessedNodes='Yes',
146 )
147 else:
148 self.default_parameters = dict(
149 Options_='',
150 Options_WriteResultsTag='Yes',
151 ParserOptions_='',
152 ParserOptions_ParserVersion=1,
153 ParserOptions_IgnoreUnprocessedNodes='Yes',
154 )
156 self.pcpot = None
157 self.lines = None
158 self.atoms = None
159 self.atoms_input = None
160 self.do_forces = False
161 # Whether to use tags of the atoms for the calculation
162 self.with_tags = with_tags
164 super().__init__(
165 restart,
166 ignore_bad_restart_file,
167 label,
168 atoms,
169 command=command,
170 profile=profile,
171 **kwargs,
172 )
174 # Determine number of spin channels
175 try:
176 entry = kwargs['Hamiltonian_SpinPolarisation']
177 spinpol = 'colinear' in entry.lower()
178 except KeyError:
179 spinpol = False
180 self.nspin = 2 if spinpol else 1
182 # kpoint stuff by ase
183 self.kpts = kpts
184 self.kpts_coord = None
186 if self.kpts is not None:
187 initkey = 'Hamiltonian_KPointsAndWeights'
188 mp_mesh = None
189 offsets = None
191 if isinstance(self.kpts, dict):
192 if 'path' in self.kpts:
193 # kpts is path in Brillouin zone
194 self.parameters[initkey + '_'] = 'Klines '
195 self.kpts_coord = kpts2ndarray(self.kpts, atoms=atoms)
196 else:
197 # kpts is (implicit) definition of
198 # Monkhorst-Pack grid
199 self.parameters[initkey + '_'] = 'SupercellFolding '
200 mp_mesh, offsets = kpts2sizeandoffsets(
201 atoms=atoms, **self.kpts
202 )
203 elif np.array(self.kpts).ndim == 1:
204 # kpts is Monkhorst-Pack grid
205 self.parameters[initkey + '_'] = 'SupercellFolding '
206 mp_mesh = self.kpts
207 offsets = [0.0] * 3
208 elif np.array(self.kpts).ndim == 2:
209 # kpts is (N x 3) list/array of k-point coordinates
210 # each will be given equal weight
211 self.parameters[initkey + '_'] = ''
212 self.kpts_coord = np.array(self.kpts)
213 else:
214 raise ValueError('Illegal kpts definition:' + str(self.kpts))
216 if mp_mesh is not None:
217 eps = 1e-10
218 for i in range(3):
219 key = initkey + '_empty%03d' % i
220 val = [mp_mesh[i] if j == i else 0 for j in range(3)]
221 self.parameters[key] = ' '.join(map(str, val))
222 offsets[i] *= mp_mesh[i]
223 assert abs(offsets[i]) < eps or abs(offsets[i] - 0.5) < eps
224 # DFTB+ uses a different offset convention, where
225 # the k-point mesh is already Gamma-centered prior
226 # to the addition of any offsets
227 if mp_mesh[i] % 2 == 0:
228 offsets[i] += 0.5
229 key = initkey + '_empty%03d' % 3
230 self.parameters[key] = ' '.join(map(str, offsets))
232 elif self.kpts_coord is not None:
233 for i, c in enumerate(self.kpts_coord):
234 key = initkey + '_empty%09d' % i
235 c_str = ' '.join(map(str, c))
236 if 'Klines' in self.parameters[initkey + '_']:
237 c_str = '1 ' + c_str
238 else:
239 c_str += ' 1.0'
240 self.parameters[key] = c_str
242 def write_dftb_in(self, outfile):
243 """Write the innput file for the dftb+ calculation.
244 Geometry is taken always from the file 'geo_end.gen'.
245 """
247 outfile.write('Geometry = GenFormat { \n')
248 outfile.write(' <<< "geo_end.gen" \n')
249 outfile.write('} \n')
250 outfile.write(' \n')
252 params = self.parameters.copy()
254 s = 'Hamiltonian_MaxAngularMomentum_'
255 for key in params:
256 if key.startswith(s) and len(key) > len(s):
257 break
258 else:
259 if params.get('Hamiltonian_', 'DFTB') == 'DFTB':
260 # User didn't specify max angular momenta. Get them from
261 # the .skf files:
262 symbols = self.atoms.get_chemical_symbols()
263 if self.with_tags:
264 tags = set(self.atoms.get_tags())
265 symbols = [
266 _s + str(tag)
267 for _s, tag in zip(
268 self.atoms.get_chemical_symbols(), tags
269 )
270 ]
271 symbols = set(symbols)
272 for symbol in symbols:
273 path = os.path.join(
274 self.slako_dir, '{0}-{0}.skf'.format(symbol)
275 )
276 l = read_max_angular_momentum(path)
277 params[s + symbol] = '"{}"'.format('spdf'[l])
279 if self.do_forces:
280 params['Analysis_'] = ''
281 params['Analysis_CalculateForces'] = 'Yes'
283 # --------MAIN KEYWORDS-------
284 previous_key = 'dummy_'
285 myspace = ' '
286 for key, value in sorted(params.items()):
287 current_depth = key.rstrip('_').count('_')
288 previous_depth = previous_key.rstrip('_').count('_')
289 for my_backslash in reversed(range(previous_depth - current_depth)):
290 outfile.write(3 * (1 + my_backslash) * myspace + '} \n')
291 outfile.write(3 * current_depth * myspace)
292 if key.endswith('_') and len(value) > 0:
293 outfile.write(
294 key.rstrip('_').rsplit('_')[-1]
295 + ' = '
296 + str(value)
297 + '{ \n'
298 )
299 elif (
300 key.endswith('_') and (len(value) == 0) and current_depth == 0
301 ): # E.g. 'Options {'
302 outfile.write(
303 key.rstrip('_').rsplit('_')[-1] + ' ' + str(value) + '{ \n'
304 )
305 elif (
306 key.endswith('_') and (len(value) == 0) and current_depth > 0
307 ): # E.g. 'Hamiltonian_Max... = {'
308 outfile.write(
309 key.rstrip('_').rsplit('_')[-1]
310 + ' = '
311 + str(value)
312 + '{ \n'
313 )
314 elif key.count('_empty') == 1:
315 outfile.write(str(value) + ' \n')
316 elif (key == 'Hamiltonian_ReadInitialCharges') and (
317 str(value).upper() == 'YES'
318 ):
319 f1 = os.path.isfile(self.directory + os.sep + 'charges.dat')
320 f2 = os.path.isfile(self.directory + os.sep + 'charges.bin')
321 if not (f1 or f2):
322 print('charges.dat or .bin not found, switching off guess')
323 value = 'No'
324 outfile.write(key.rsplit('_')[-1] + ' = ' + str(value) + ' \n')
325 else:
326 outfile.write(key.rsplit('_')[-1] + ' = ' + str(value) + ' \n')
327 if self.pcpot is not None and ('DFTB' in str(value)):
328 outfile.write(' ElectricField = { \n')
329 outfile.write(' PointCharges = { \n')
330 outfile.write(
331 ' CoordsAndCharges [Angstrom] = DirectRead { \n'
332 )
333 outfile.write(
334 ' Records = '
335 + str(len(self.pcpot.mmcharges))
336 + ' \n'
337 )
338 outfile.write(
339 ' File = "dftb_external_charges.dat" \n'
340 )
341 outfile.write(' } \n')
342 outfile.write(' } \n')
343 outfile.write(' } \n')
344 previous_key = key
345 current_depth = key.rstrip('_').count('_')
346 for my_backslash in reversed(range(current_depth)):
347 outfile.write(3 * my_backslash * myspace + '} \n')
349 def check_state(self, atoms):
350 system_changes = FileIOCalculator.check_state(self, atoms)
351 # Ignore unit cell for molecules:
352 if not atoms.pbc.any() and 'cell' in system_changes:
353 system_changes.remove('cell')
354 if self.pcpot and self.pcpot.mmpositions is not None:
355 system_changes.append('positions')
356 return system_changes
358 def write_input(self, atoms, properties=None, system_changes=None):
359 from ase.io.gen import write_gen
361 if properties is not None:
362 if 'forces' in properties or 'stress' in properties:
363 self.do_forces = True
364 FileIOCalculator.write_input(self, atoms, properties, system_changes)
365 with open(os.path.join(self.directory, 'dftb_in.hsd'), 'w') as fd:
366 self.write_dftb_in(fd)
367 write_gen(
368 os.path.join(self.directory, 'geo_end.gen'),
369 atoms,
370 with_tags=self.with_tags,
371 )
372 # self.atoms is none until results are read out,
373 # then it is set to the ones at writing input
374 self.atoms_input = atoms
375 self.atoms = None
376 if self.pcpot:
377 self.pcpot.write_mmcharges('dftb_external_charges.dat')
379 def read_results(self):
380 """all results are read from results.tag file
381 It will be destroyed after it is read to avoid
382 reading it once again after some runtime error"""
384 with open(os.path.join(self.directory, 'results.tag')) as fd:
385 self.lines = fd.readlines()
387 self.atoms = self.atoms_input
388 charges, energy, dipole = self.read_charges_energy_dipole()
389 if charges is not None:
390 self.results['charges'] = charges
391 self.results['energy'] = energy
392 if dipole is not None:
393 self.results['dipole'] = dipole
394 if self.do_forces:
395 forces = self.read_forces()
396 self.results['forces'] = forces
397 self.mmpositions = None
399 # stress stuff begins
400 sstring = 'stress'
401 have_stress = False
402 stress = []
403 for iline, line in enumerate(self.lines):
404 if sstring in line:
405 have_stress = True
406 start = iline + 1
407 end = start + 3
408 for i in range(start, end):
409 cell = [float(x) for x in self.lines[i].split()]
410 stress.append(cell)
411 if have_stress:
412 stress = -np.array(stress) * Hartree / Bohr**3
413 self.results['stress'] = stress.flat[[0, 4, 8, 5, 2, 1]]
414 # stress stuff ends
416 # eigenvalues and fermi levels
417 fermi_levels = self.read_fermi_levels()
418 if fermi_levels is not None:
419 self.results['fermi_levels'] = fermi_levels
421 eigenvalues = self.read_eigenvalues()
422 if eigenvalues is not None:
423 self.results['eigenvalues'] = eigenvalues
425 # calculation was carried out with atoms written in write_input
426 os.remove(os.path.join(self.directory, 'results.tag'))
428 def read_forces(self):
429 """Read Forces from dftb output file (results.tag)."""
430 from ase.units import Bohr, Hartree
432 # Initialise the indices so their scope
433 # reaches outside of the for loop
434 index_force_begin = -1
435 index_force_end = -1
437 # Force line indexes
438 for iline, line in enumerate(self.lines):
439 fstring = 'forces '
440 if line.find(fstring) >= 0:
441 index_force_begin = iline + 1
442 line1 = line.replace(':', ',')
443 index_force_end = iline + 1 + int(line1.split(',')[-1])
444 break
446 gradients = []
447 for j in range(index_force_begin, index_force_end):
448 word = self.lines[j].split()
449 gradients.append([float(word[k]) for k in range(3)])
451 return np.array(gradients) * Hartree / Bohr
453 def read_charges_energy_dipole(self):
454 """Get partial charges on atoms
455 in case we cannot find charges they are set to None
456 """
457 with open(os.path.join(self.directory, 'detailed.out')) as fd:
458 lines = fd.readlines()
460 for line in lines:
461 if line.strip().startswith('Total energy:'):
462 energy = float(line.split()[2]) * Hartree
463 break
465 qm_charges = []
466 for n, line in enumerate(lines):
467 if 'Atom' and 'Charge' in line:
468 chargestart = n + 1
469 break
470 else:
471 # print('Warning: did not find DFTB-charges')
472 # print('This is ok if flag SCC=No')
473 return None, energy, None
475 lines1 = lines[chargestart : (chargestart + len(self.atoms))]
476 for line in lines1:
477 qm_charges.append(float(line.split()[-1]))
479 dipole = None
480 for line in lines:
481 if 'Dipole moment:' in line and 'au' in line:
482 line = line.replace('Dipole moment:', '').replace('au', '')
483 dipole = np.array(line.split(), dtype=float) * Bohr
485 return np.array(qm_charges), energy, dipole
487 def get_charges(self, atoms):
488 """Get the calculated charges
489 this is inhereted to atoms object"""
490 if 'charges' in self.results:
491 return self.results['charges']
492 else:
493 return None
495 def read_eigenvalues(self):
496 """Read Eigenvalues from dftb output file (results.tag).
497 Unfortunately, the order seems to be scrambled."""
498 # Eigenvalue line indexes
499 index_eig_begin = None
500 for iline, line in enumerate(self.lines):
501 fstring = 'eigenvalues '
502 if line.find(fstring) >= 0:
503 index_eig_begin = iline + 1
504 line1 = line.replace(':', ',')
505 ncol, nband, nkpt, nspin = map(int, line1.split(',')[-4:])
506 break
507 else:
508 return None
510 # Take into account that the last row may lack
511 # columns if nkpt * nspin * nband % ncol != 0
512 nrow = int(np.ceil(nkpt * nspin * nband * 1.0 / ncol))
513 index_eig_end = index_eig_begin + nrow
514 ncol_last = len(self.lines[index_eig_end - 1].split())
515 # XXX dirty fix
516 self.lines[index_eig_end - 1] = self.lines[
517 index_eig_end - 1
518 ].strip() + ' 0.0 ' * (ncol - ncol_last)
520 eig = np.loadtxt(self.lines[index_eig_begin:index_eig_end]).flatten()
521 eig *= Hartree
522 N = nkpt * nband
523 eigenvalues = [
524 eig[i * N : (i + 1) * N].reshape((nkpt, nband))
525 for i in range(nspin)
526 ]
528 return eigenvalues
530 def read_fermi_levels(self):
531 """Read Fermi level(s) from dftb output file (results.tag)."""
532 # Fermi level line indexes
533 for iline, line in enumerate(self.lines):
534 fstring = 'fermi_level '
535 if line.find(fstring) >= 0:
536 index_fermi = iline + 1
537 break
538 else:
539 return None
541 fermi_levels = []
542 words = self.lines[index_fermi].split()
543 assert len(words) in [1, 2], 'Expected either 1 or 2 Fermi levels'
545 for word in words:
546 e = float(word)
547 # In non-spin-polarized calculations with DFTB+ v17.1,
548 # two Fermi levels are given, with the second one being 0,
549 # but we don't want to add that one to the list
550 if abs(e) > 1e-8:
551 fermi_levels.append(e)
553 return np.array(fermi_levels) * Hartree
555 def get_ibz_k_points(self):
556 return self.kpts_coord.copy()
558 def get_number_of_spins(self):
559 return self.nspin
561 def get_eigenvalues(self, kpt=0, spin=0):
562 return self.results['eigenvalues'][spin][kpt].copy()
564 def get_fermi_levels(self):
565 return self.results['fermi_levels'].copy()
567 def get_fermi_level(self):
568 return max(self.get_fermi_levels())
570 def embed(self, mmcharges=None, directory='./'):
571 """Embed atoms in point-charges (mmcharges)"""
572 self.pcpot = PointChargePotential(mmcharges, self.directory)
573 return self.pcpot
576class PointChargePotential:
577 def __init__(self, mmcharges, directory='./'):
578 """Point-charge potential for DFTB+."""
579 self.mmcharges = mmcharges
580 self.directory = directory
581 self.mmpositions = None
582 self.mmforces = None
584 def set_positions(self, mmpositions):
585 self.mmpositions = mmpositions
587 def set_charges(self, mmcharges):
588 self.mmcharges = mmcharges
590 def write_mmcharges(self, filename):
591 """mok all
592 write external charges as monopoles for dftb+.
594 """
595 if self.mmcharges is None:
596 print('DFTB: Warning: not writing exernal charges ')
597 return
598 with open(os.path.join(self.directory, filename), 'w') as charge_file:
599 for [pos, charge] in zip(self.mmpositions, self.mmcharges):
600 [x, y, z] = pos
601 charge_file.write(
602 '%12.6f %12.6f %12.6f %12.6f \n' % (x, y, z, charge)
603 )
605 def get_forces(self, calc, get_forces=True):
606 """returns forces on point charges if the flag get_forces=True"""
607 if get_forces:
608 return self.read_forces_on_pointcharges()
609 else:
610 return np.zeros_like(self.mmpositions)
612 def read_forces_on_pointcharges(self):
613 """Read Forces from dftb output file (results.tag)."""
614 from ase.units import Bohr, Hartree
616 with open(os.path.join(self.directory, 'detailed.out')) as fd:
617 lines = fd.readlines()
619 external_forces = []
620 for n, line in enumerate(lines):
621 if 'Forces on external charges' in line:
622 chargestart = n + 1
623 break
624 else:
625 raise RuntimeError(
626 'Problem in reading forces on MM external-charges'
627 )
628 lines1 = lines[chargestart : (chargestart + len(self.mmcharges))]
629 for line in lines1:
630 external_forces.append([float(i) for i in line.split()])
631 return np.array(external_forces) * Hartree / Bohr
634def read_max_angular_momentum(path):
635 """Read maximum angular momentum from .skf file.
637 See dftb.org for A detailed description of the Slater-Koster file format.
638 """
639 with open(path) as fd:
640 line = fd.readline()
641 if line[0] == '@':
642 # Extended format
643 fd.readline()
644 l = 3
645 pos = 9
646 else:
647 # Simple format:
648 l = 2
649 pos = 7
651 # Sometimes there ar commas, sometimes not:
652 line = fd.readline().replace(',', ' ')
654 occs = [float(f) for f in line.split()[pos : pos + l + 1]]
655 for f in occs:
656 if f > 0.0:
657 return l
658 l -= 1