Coverage for ase/io/res.py: 94.77%
153 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"""
2SHELX (.res) input/output
4Read/write files in SHELX (.res) file format.
6Format documented at http://shelx.uni-ac.gwdg.de/SHELX/
8Written by Martin Uhren and Georg Schusteritsch.
9Adapted for ASE by James Kermode.
10"""
12import glob
13import re
15from ase.atoms import Atoms
16from ase.calculators.calculator import Calculator
17from ase.calculators.singlepoint import SinglePointCalculator
18from ase.geometry import cell_to_cellpar, cellpar_to_cell
20__all__ = ['Res', 'read_res', 'write_res']
23class Res:
24 """
25 Object for representing the data in a Res file.
26 Most attributes can be set directly.
28 Args:
29 atoms (Atoms): Atoms object.
31 .. attribute:: atoms
33 Associated Atoms object.
35 .. attribute:: name
37 The name of the structure.
39 .. attribute:: pressure
41 The external pressure.
43 .. attribute:: energy
45 The internal energy of the structure.
47 .. attribute:: spacegroup
49 The space group of the structure.
51 .. attribute:: times_found
53 The number of times the structure was found.
54 """
56 def __init__(
57 self,
58 atoms,
59 name=None,
60 pressure=None,
61 energy=None,
62 spacegroup=None,
63 times_found=None,
64 ):
65 self.atoms_ = atoms
66 if name is None:
67 name = atoms.info.get('name')
68 if pressure is None:
69 pressure = atoms.info.get('pressure')
70 if spacegroup is None:
71 spacegroup = atoms.info.get('spacegroup')
72 if times_found is None:
73 times_found = atoms.info.get('times_found')
74 self.name = name
75 self.pressure = pressure
76 self.energy = energy
77 self.spacegroup = spacegroup
78 self.times_found = times_found
80 @property
81 def atoms(self):
82 """
83 Returns Atoms object associated with this Res.
84 """
85 return self.atoms_
87 @staticmethod
88 def from_file(filename):
89 """
90 Reads a Res from a file.
92 Args:
93 filename (str): File name containing Res data.
95 Returns
96 -------
97 Res object.
98 """
99 with open(filename) as fd:
100 return Res.from_string(fd.read())
102 @staticmethod
103 def parse_title(line):
104 info = {}
106 tokens = line.split()
107 num_tokens = len(tokens)
108 # 1 = Name
109 if num_tokens <= 1:
110 return info
111 info['name'] = tokens[1]
112 # 2 = Pressure
113 if num_tokens <= 2:
114 return info
115 info['pressure'] = float(tokens[2])
116 # 3 = Volume
117 # 4 = Internal energy
118 if num_tokens <= 4:
119 return info
120 info['energy'] = float(tokens[4])
121 # 5 = Spin density, 6 - Abs spin density
122 # 7 = Space group OR num atoms (new format ONLY)
123 idx = 7
124 if tokens[idx][0] != '(':
125 idx += 1
127 if num_tokens <= idx:
128 return info
129 info['spacegroup'] = tokens[idx][1 : len(tokens[idx]) - 1]
130 # idx + 1 = n, idx + 2 = -
131 # idx + 3 = times found
132 if num_tokens <= idx + 3:
133 return info
134 info['times_found'] = int(tokens[idx + 3])
136 return info
138 @staticmethod
139 def from_string(data):
140 """
141 Reads a Res from a string.
143 Args:
144 data (str): string containing Res data.
146 Returns
147 -------
148 Res object.
149 """
150 abc = []
151 ang = []
152 sp = []
153 coords = []
154 info = {}
155 coord_patt = re.compile(
156 r"""(\w+)\s+
157 ([0-9]+)\s+
158 ([0-9\-\.]+)\s+
159 ([0-9\-\.]+)\s+
160 ([0-9\-\.]+)\s+
161 ([0-9\-\.]+)""",
162 re.VERBOSE,
163 )
164 lines = data.splitlines()
165 line_no = 0
166 while line_no < len(lines):
167 line = lines[line_no]
168 tokens = line.split()
169 if tokens:
170 if tokens[0] == 'TITL':
171 try:
172 info = Res.parse_title(line)
173 except (ValueError, IndexError):
174 info = {}
175 elif tokens[0] == 'CELL' and len(tokens) == 8:
176 abc = [float(tok) for tok in tokens[2:5]]
177 ang = [float(tok) for tok in tokens[5:8]]
178 elif tokens[0] == 'SFAC':
179 for atom_line in lines[line_no:]:
180 if line.strip() == 'END':
181 break
182 else:
183 match = coord_patt.search(atom_line)
184 if match:
185 sp.append(match.group(1)) # 1-indexed
186 cs = match.groups()[2:5]
187 coords.append([float(c) for c in cs])
188 line_no += 1 # Make sure the global is updated
189 line_no += 1
191 return Res(
192 Atoms(
193 symbols=sp,
194 scaled_positions=coords,
195 cell=cellpar_to_cell(list(abc) + list(ang)),
196 pbc=True,
197 info=info,
198 ),
199 info.get('name'),
200 info.get('pressure'),
201 info.get('energy'),
202 info.get('spacegroup'),
203 info.get('times_found'),
204 )
206 def get_string(self, significant_figures=6, write_info=False):
207 """
208 Returns a string to be written as a Res file.
210 Args:
211 significant_figures (int): No. of significant figures to
212 output all quantities. Defaults to 6.
214 write_info (bool): if True, format TITL line using key-value pairs
215 from atoms.info in addition to attributes stored in Res object
217 Returns
218 -------
219 String representation of Res.
220 """
222 # Title line
223 if write_info:
224 info = self.atoms.info.copy()
225 for attribute in [
226 'name',
227 'pressure',
228 'energy',
229 'spacegroup',
230 'times_found',
231 ]:
232 if getattr(self, attribute) and attribute not in info:
233 info[attribute] = getattr(self, attribute)
234 lines = [
235 'TITL ' + ' '.join([f'{k}={v}' for (k, v) in info.items()])
236 ]
237 else:
238 lines = ['TITL ' + self.print_title()]
240 # Cell
241 abc_ang = cell_to_cellpar(self.atoms.get_cell())
242 fmt = f'{{0:.{significant_figures}f}}'
243 cell = ' '.join([fmt.format(a) for a in abc_ang])
244 lines.append('CELL 1.0 ' + cell)
246 # Latt
247 lines.append('LATT -1')
249 # Atoms
250 symbols = self.atoms.get_chemical_symbols()
251 species_types = []
252 for symbol in symbols:
253 if symbol not in species_types:
254 species_types.append(symbol)
255 lines.append('SFAC ' + ' '.join(species_types))
257 fmt = '{{0}} {{1}} {{2:.{0}f}} {{3:.{0}f}} {{4:.{0}f}} 1.0'
258 fmtstr = fmt.format(significant_figures)
259 for symbol, coords in zip(symbols, self.atoms_.get_scaled_positions()):
260 lines.append(
261 fmtstr.format(
262 symbol,
263 species_types.index(symbol) + 1,
264 coords[0],
265 coords[1],
266 coords[2],
267 )
268 )
269 lines.append('END')
270 return '\n'.join(lines)
272 def __str__(self):
273 """
274 String representation of Res file.
275 """
276 return self.get_string()
278 def write_file(self, filename, **kwargs):
279 """
280 Writes Res to a file. The supported kwargs are the same as those for
281 the Res.get_string method and are passed through directly.
282 """
283 with open(filename, 'w') as fd:
284 fd.write(self.get_string(**kwargs) + '\n')
286 def print_title(self):
287 tokens = [
288 self.name,
289 self.pressure,
290 self.atoms.get_volume(),
291 self.energy,
292 0.0,
293 0.0,
294 len(self.atoms),
295 ]
296 if self.spacegroup:
297 tokens.append('(' + self.spacegroup + ')')
298 else:
299 tokens.append('(P1)')
300 if self.times_found:
301 tokens.append('n - ' + str(self.times_found))
302 else:
303 tokens.append('n - 1')
305 return ' '.join([str(tok) for tok in tokens])
308def read_res(filename, index=-1):
309 """
310 Read input in SHELX (.res) format
312 Multiple frames are read if `filename` contains a wildcard character,
313 e.g. `file_*.res`. `index` specifes which frames to retun: default is
314 last frame only (index=-1).
315 """
316 images = []
317 for fn in sorted(glob.glob(filename)):
318 res = Res.from_file(fn)
319 if res.energy:
320 calc = SinglePointCalculator(res.atoms, energy=res.energy)
321 res.atoms.calc = calc
322 images.append(res.atoms)
323 return images[index]
326def write_res(
327 filename, images, write_info=True, write_results=True, significant_figures=6
328):
329 r"""
330 Write output in SHELX (.res) format
332 To write multiple images, include a % format string in filename,
333 e.g. `file\_\%03d.res`.
335 Optionally include contents of Atoms.info dictionary if `write_info`
336 is True, and/or results from attached calculator if `write_results`
337 is True (only energy results are supported).
338 """
340 if not isinstance(images, (list, tuple)):
341 images = [images]
343 if len(images) > 1 and '%' not in filename:
344 raise RuntimeError(
345 'More than one Atoms provided but no %'
346 + ' format string found in filename'
347 )
349 for i, atoms in enumerate(images):
350 fn = filename
351 if '%' in filename:
352 fn = filename % i
353 res = Res(atoms)
354 if write_results:
355 calculator = atoms.calc
356 if calculator is not None and isinstance(calculator, Calculator):
357 energy = calculator.results.get('energy')
358 if energy is not None:
359 res.energy = energy
360 res.write_file(
361 fn, write_info=write_info, significant_figures=significant_figures
362 )