Coverage for ase/io/dmol.py: 94.16%
154 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"""
2IO functions for DMol3 file formats.
4read/write functionality for car, incoor and arc file formats
5only car format is added to known ase file extensions
6use format='dmol-arc' or 'dmol-incoor' for others
8car structure file - Angstrom and cellpar description of cell.
9incoor structure file - Bohr and cellvector describption of cell.
10 Note: incoor file not used if car file present.
11arc multiple-structure file - Angstrom and cellpar description of cell.
14The formats follow strict formatting
16car
17----
18col: 1-5 atom name
19col: 7-20 x Cartesian coordinate of atom in A
20col: 22-35 y Cartesian coordinate of atom in A
21col: 37-50 z Cartesian coordinate of atom in A
22col: 52-55 type of residue containing atom
23col: 57-63 residue sequence name relative to beginning of current molecule,
24 left justified
25col: 64-70 potential type of atom left justified
26col: 72-73 element symbol
27col: 75-80 partial charge on atom
30incoor
31-------
32$cell vectors
33 37.83609647462165 0.00000000000000 0.00000000000000
34 0.00000000000000 37.60366016124745 0.00000000000000
35 0.00000000000000 0.00000000000000 25.29020473078921
36$coordinates
37Si 15.94182672614820 1.85274838936809 16.01426481346124
38Si 4.45559370448989 2.68957177851318 -0.05326937257442
39$end
42arc
43----
44multiple images of car format separated with $end
47"""
49from datetime import datetime
51import numpy as np
53from ase import Atom, Atoms
54from ase.geometry.cell import cell_to_cellpar, cellpar_to_cell
55from ase.units import Bohr
56from ase.utils import reader, writer
59@writer
60def write_dmol_car(fd, atoms):
61 """Write a dmol car-file from an Atoms object
63 Notes
64 -----
65 The positions written to file are rotated as to align with the cell when
66 reading (due to cellpar information)
67 Can not handle multiple images.
68 Only allows for pbc 111 or 000.
69 """
71 fd.write('!BIOSYM archive 3\n')
72 dt = datetime.now()
74 symbols = atoms.get_chemical_symbols()
75 if np.all(atoms.pbc):
76 # Rotate positions so they will align with cellpar cell
77 cellpar = cell_to_cellpar(atoms.cell)
78 new_cell = cellpar_to_cell(cellpar)
79 lstsq_fit = np.linalg.lstsq(atoms.cell, new_cell, rcond=-1)
80 # rcond=-1 silences FutureWarning in numpy 1.14
81 R = lstsq_fit[0]
82 positions = np.dot(atoms.positions, R)
84 fd.write('PBC=ON\n\n')
85 fd.write('!DATE %s\n' % dt.strftime('%b %d %H:%M:%S %Y'))
86 fd.write('PBC %9.5f %9.5f %9.5f %9.5f %9.5f %9.5f\n' % tuple(cellpar))
87 elif not np.any(atoms.pbc): # [False,False,False]
88 fd.write('PBC=OFF\n\n')
89 fd.write('!DATE %s\n' % dt.strftime('%b %d %H:%M:%S %Y'))
90 positions = atoms.positions
91 else:
92 raise ValueError('PBC must be all true or all false for .car format')
94 for i, (sym, pos) in enumerate(zip(symbols, positions)):
95 fd.write(
96 '%-6s %12.8f %12.8f %12.8f XXXX 1 xx %-2s '
97 '0.000\n' % (sym + str(i + 1), pos[0], pos[1], pos[2], sym)
98 )
99 fd.write('end\nend\n')
102@reader
103def read_dmol_car(fd):
104 """Read a dmol car-file and return an Atoms object.
106 Notes
107 -----
108 Cell is constructed from cellpar so orientation of cell might be off.
109 """
111 lines = fd.readlines()
112 atoms = Atoms()
114 start_line = 4
116 if lines[1][4:6] == 'ON':
117 start_line += 1
118 cell_dat = np.array([float(fld) for fld in lines[4].split()[1:7]])
119 cell = cellpar_to_cell(cell_dat)
120 pbc = [True, True, True]
121 else:
122 cell = np.zeros((3, 3))
123 pbc = [False, False, False]
125 symbols = []
126 positions = []
127 for line in lines[start_line:]:
128 if line.startswith('end'):
129 break
130 flds = line.split()
131 symbols.append(flds[7])
132 positions.append(flds[1:4])
133 atoms.append(Atom(flds[7], flds[1:4]))
134 atoms = Atoms(symbols=symbols, positions=positions, cell=cell, pbc=pbc)
135 return atoms
138@writer
139def write_dmol_incoor(fd, atoms, bohr=True):
140 """Write a dmol incoor-file from an Atoms object
142 Notes
143 -----
144 Only used for pbc 111.
145 Can not handle multiple images.
146 DMol3 expect data in .incoor files to be in bohr, if bohr is false however
147 the data is written in Angstroms.
148 """
150 if not np.all(atoms.pbc):
151 raise ValueError('PBC must be all true for .incoor format')
153 if bohr:
154 cell = atoms.cell / Bohr
155 positions = atoms.positions / Bohr
156 else:
157 cell = atoms.cell
158 positions = atoms.positions
160 fd.write('$cell vectors\n')
161 fd.write(
162 ' {:18.14f} {:18.14f} {:18.14f}\n'.format(
163 cell[0, 0], cell[0, 1], cell[0, 2]
164 )
165 )
166 fd.write(
167 ' {:18.14f} {:18.14f} {:18.14f}\n'.format(
168 cell[1, 0], cell[1, 1], cell[1, 2]
169 )
170 )
171 fd.write(
172 ' {:18.14f} {:18.14f} {:18.14f}\n'.format(
173 cell[2, 0], cell[2, 1], cell[2, 2]
174 )
175 )
177 fd.write('$coordinates\n')
178 for a, pos in zip(atoms, positions):
179 fd.write(
180 '%-12s%18.14f %18.14f %18.14f \n'
181 % (a.symbol, pos[0], pos[1], pos[2])
182 )
183 fd.write('$end\n')
186@reader
187def read_dmol_incoor(fd, bohr=True):
188 """Reads an incoor file and returns an atoms object.
190 Notes
191 -----
192 If bohr is True then incoor is assumed to be in bohr and the data
193 is rescaled to Angstrom.
194 """
196 lines = fd.readlines()
197 symbols = []
198 positions = []
199 for i, line in enumerate(lines):
200 if line.startswith('$cell vectors'):
201 cell = np.zeros((3, 3))
202 for j, line in enumerate(lines[i + 1 : i + 4]):
203 cell[j, :] = [float(fld) for fld in line.split()]
204 if line.startswith('$coordinates'):
205 j = i + 1
206 while True:
207 if lines[j].startswith('$end'):
208 break
209 flds = lines[j].split()
210 symbols.append(flds[0])
211 positions.append(flds[1:4])
212 j += 1
213 atoms = Atoms(symbols=symbols, positions=positions, cell=cell, pbc=True)
214 if bohr:
215 atoms.cell = atoms.cell * Bohr
216 atoms.positions = atoms.positions * Bohr
217 return atoms
220@writer
221def write_dmol_arc(fd, images):
222 """Writes all images to file filename in arc format.
224 Similar to the .car format only pbc 111 or 000 is supported.
225 """
227 fd.write('!BIOSYM archive 3\n')
228 if np.all(images[0].pbc):
229 fd.write('PBC=ON\n\n')
230 # Rotate positions so they will align with cellpar cell
231 elif not np.any(images[0].pbc):
232 fd.write('PBC=OFF\n\n')
233 else:
234 raise ValueError('PBC must be all true or all false for .arc format')
235 for atoms in images:
236 dt = datetime.now()
237 symbols = atoms.get_chemical_symbols()
238 if np.all(atoms.pbc):
239 cellpar = cell_to_cellpar(atoms.cell)
240 new_cell = cellpar_to_cell(cellpar)
241 lstsq_fit = np.linalg.lstsq(atoms.cell, new_cell, rcond=-1)
242 R = lstsq_fit[0]
243 fd.write('!DATE %s\n' % dt.strftime('%b %d %H:%m:%S %Y'))
244 fd.write(
245 'PBC %9.5f %9.5f %9.5f %9.5f %9.5f %9.5f\n' % tuple(cellpar)
246 )
247 positions = np.dot(atoms.positions, R)
248 elif not np.any(atoms.pbc): # [False,False,False]
249 fd.write('!DATE %s\n' % dt.strftime('%b %d %H:%m:%S %Y'))
250 positions = atoms.positions
251 else:
252 raise ValueError(
253 'PBC must be all true or all false for .arc format'
254 )
255 for i, (sym, pos) in enumerate(zip(symbols, positions)):
256 fd.write(
257 '%-6s %12.8f %12.8f %12.8f XXXX 1 xx %-2s '
258 '0.000\n' % (sym + str(i + 1), pos[0], pos[1], pos[2], sym)
259 )
260 fd.write('end\nend\n')
261 fd.write('\n')
264@reader
265def read_dmol_arc(fd, index=-1):
266 """Read a dmol arc-file and return a series of Atoms objects (images)."""
268 lines = fd.readlines()
269 images = []
271 if lines[1].startswith('PBC=ON'):
272 pbc = True
273 elif lines[1].startswith('PBC=OFF'):
274 pbc = False
275 else:
276 raise RuntimeError('Could not read pbc from second line in file')
278 i = 0
279 while i < len(lines):
280 cell = np.zeros((3, 3))
281 symbols = []
282 positions = []
283 # parse single image
284 if lines[i].startswith('!DATE'):
285 # read cell
286 if pbc:
287 cell_dat = np.array(
288 [float(fld) for fld in lines[i + 1].split()[1:7]]
289 )
290 cell = cellpar_to_cell(cell_dat)
291 i += 1
292 i += 1
293 # read atoms
294 while not lines[i].startswith('end'):
295 flds = lines[i].split()
296 symbols.append(flds[7])
297 positions.append(flds[1:4])
298 i += 1
299 image = Atoms(
300 symbols=symbols, positions=positions, cell=cell, pbc=pbc
301 )
302 images.append(image)
303 if len(images) == index:
304 return images[-1]
305 i += 1
307 # return requested images, code borrowed from ase/io/trajectory.py
308 if isinstance(index, int):
309 return images[index]
310 else:
311 from ase.io.formats import index2range
313 indices = index2range(index, len(images))
314 return [images[j] for j in indices]