Coverage for ase/io/dftb.py: 92.91%
127 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
1from collections.abc import Sequence
3import numpy as np
5from ase.atoms import Atoms
6from ase.utils import reader, writer
9@reader
10def read_dftb(fd):
11 """Method to read coordinates from the Geometry section
12 of a DFTB+ input file (typically called "dftb_in.hsd").
14 As described in the DFTB+ manual, this section can be
15 in a number of different formats. This reader supports
16 the GEN format and the so-called "explicit" format.
18 The "explicit" format is unique to DFTB+ input files.
19 The GEN format can also be used in a stand-alone fashion,
20 as coordinate files with a `.gen` extension. Reading and
21 writing such files is implemented in `ase.io.gen`.
22 """
23 lines = fd.readlines()
25 atoms_pos = []
26 atom_symbols = []
27 type_names = []
28 my_pbc = False
29 fractional = False
30 mycell = []
32 for iline, line in enumerate(lines):
33 if line.strip().startswith('#'):
34 pass
35 elif 'genformat' in line.lower():
36 natoms = int(lines[iline + 1].split()[0])
37 if lines[iline + 1].split()[1].lower() == 's':
38 my_pbc = True
39 elif lines[iline + 1].split()[1].lower() == 'f':
40 my_pbc = True
41 fractional = True
43 symbols = lines[iline + 2].split()
45 for i in range(natoms):
46 index = iline + 3 + i
47 aindex = int(lines[index].split()[1]) - 1
48 atom_symbols.append(symbols[aindex])
50 position = [float(p) for p in lines[index].split()[2:]]
51 atoms_pos.append(position)
53 if my_pbc:
54 for i in range(3):
55 index = iline + 4 + natoms + i
56 cell = [float(c) for c in lines[index].split()]
57 mycell.append(cell)
58 else:
59 if 'TypeNames' in line:
60 col = line.split()
61 for i in range(3, len(col) - 1):
62 type_names.append(col[i].strip('"'))
63 elif 'Periodic' in line:
64 if 'Yes' in line:
65 my_pbc = True
66 elif 'LatticeVectors' in line:
67 for imycell in range(3):
68 extraline = lines[iline + imycell + 1]
69 cols = extraline.split()
70 mycell.append(
71 [float(cols[0]), float(cols[1]), float(cols[2])]
72 )
73 else:
74 pass
76 if not my_pbc:
77 mycell = [0.0] * 3
79 start_reading_coords = False
80 stop_reading_coords = False
81 for line in lines:
82 if line.strip().startswith('#'):
83 pass
84 else:
85 if 'TypesAndCoordinates' in line:
86 start_reading_coords = True
87 if start_reading_coords:
88 if '}' in line:
89 stop_reading_coords = True
90 if (
91 start_reading_coords
92 and not stop_reading_coords
93 and 'TypesAndCoordinates' not in line
94 ):
95 typeindexstr, xxx, yyy, zzz = line.split()[:4]
96 typeindex = int(typeindexstr)
97 symbol = type_names[typeindex - 1]
98 atom_symbols.append(symbol)
99 atoms_pos.append([float(xxx), float(yyy), float(zzz)])
101 if fractional:
102 atoms = Atoms(
103 scaled_positions=atoms_pos,
104 symbols=atom_symbols,
105 cell=mycell,
106 pbc=my_pbc,
107 )
108 elif not fractional:
109 atoms = Atoms(
110 positions=atoms_pos, symbols=atom_symbols, cell=mycell, pbc=my_pbc
111 )
113 return atoms
116def read_dftb_velocities(atoms, filename):
117 """Method to read velocities (AA/ps) from DFTB+ output file geo_end.xyz"""
118 from ase.units import second
120 # AA/ps -> ase units
121 AngdivPs2ASE = 1.0 / (1e-12 * second)
123 with open(filename) as fd:
124 lines = fd.readlines()
126 # remove empty lines
127 lines_ok = []
128 for line in lines:
129 if line.rstrip():
130 lines_ok.append(line)
132 velocities = []
133 natoms = len(atoms)
134 last_lines = lines_ok[-natoms:]
135 for iline, line in enumerate(last_lines):
136 inp = line.split()
137 velocities.append(
138 [
139 float(inp[5]) * AngdivPs2ASE,
140 float(inp[6]) * AngdivPs2ASE,
141 float(inp[7]) * AngdivPs2ASE,
142 ]
143 )
145 atoms.set_velocities(velocities)
146 return atoms
149@reader
150def read_dftb_lattice(fileobj, images=None):
151 """Read lattice vectors from MD and return them as a list.
153 If a molecules are parsed add them there."""
154 if images is not None:
155 append = True
156 if hasattr(images, 'get_positions'):
157 images = [images]
158 else:
159 append = False
161 fileobj.seek(0)
162 lattices = []
163 for line in fileobj:
164 if 'Lattice vectors' in line:
165 vec = []
166 for _ in range(3):
167 line = fileobj.readline().split()
168 try:
169 line = [float(x) for x in line]
170 except ValueError:
171 raise ValueError(
172 'Lattice vector elements should be of type float.'
173 )
174 vec.extend(line)
175 lattices.append(np.array(vec).reshape((3, 3)))
177 if append:
178 if len(images) != len(lattices):
179 raise ValueError(
180 'Length of images given does not match number of '
181 'cell vectors found'
182 )
184 for i, atoms in enumerate(images):
185 atoms.set_cell(lattices[i])
186 # DFTB+ only supports 3D PBC
187 atoms.set_pbc(True)
188 return None
189 else:
190 return lattices
193@writer
194def write_dftb(
195 fileobj,
196 images: Atoms | Sequence[Atoms],
197 fractional: bool = False,
198):
199 """Write structure in GEN format (refer to DFTB+ manual).
200 Multiple snapshots are not allowed."""
201 from ase.io.gen import write_gen
203 write_gen(fileobj, images, fractional=fractional)
206def write_dftb_velocities(atoms, filename):
207 """Method to write velocities (in atomic units) from ASE
208 to a file to be read by dftb+
209 """
210 from ase.units import AUT, Bohr
212 # ase units -> atomic units
213 ASE2au = Bohr / AUT
215 with open(filename, 'w') as fd:
216 velocities = atoms.get_velocities()
217 for velocity in velocities:
218 fd.write(
219 ' %19.16f %19.16f %19.16f \n'
220 % (
221 velocity[0] / ASE2au,
222 velocity[1] / ASE2au,
223 velocity[2] / ASE2au,
224 )
225 )