Coverage for ase/io/magres.py: 79.65%
226 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 provides I/O functions for the MAGRES file format, introduced
2by CASTEP as an output format to store structural data and ab-initio
3calculated NMR parameters.
4Authors: Simone Sturniolo (ase implementation), Tim Green (original magres
5 parser code)
6"""
8from collections import OrderedDict
10import numpy as np
12import ase.io._magres as _magres
13import ase.units
14from ase.atoms import Atoms
15from ase.calculators.singlepoint import SinglePointDFTCalculator
16from ase.spacegroup import Spacegroup
17from ase.spacegroup.spacegroup import SpacegroupNotFoundError
19_mprops = {
20 'ms': ('sigma', 1),
21 'sus': ('S', 0),
22 'efg': ('V', 1),
23 'isc': ('K', 2),
24}
25# (matrix name, number of atoms in interaction) for various magres quantities
28def read_magres(fd, include_unrecognised=False):
29 """Read magres file."""
31 block_parsers = {
32 'magres': _magres.parse_magres_block,
33 'atoms': _magres.parse_atoms_block,
34 'calculation': _magres.parse_generic_block,
35 }
37 file_contents = fd.read()
39 # This works as a validity check
40 version = _magres.get_version(file_contents)
41 if version is None:
42 # This isn't even a .magres file!
43 raise RuntimeError('File is not in standard Magres format')
44 blocks = _magres.parse_blocks(file_contents)
46 data_dict = {}
48 for block_data in blocks:
49 block = _magres.parse_block(block_data)
51 if block[0] in block_parsers:
52 block_dict = block_parsers[block[0]](block)
53 data_dict[block[0]] = block_dict
54 else:
55 # Throw in the text content of blocks we don't recognise
56 if include_unrecognised:
57 data_dict[block[0]] = block_data[1]
59 # Now the loaded data must be turned into an ASE Atoms object
61 # First check if the file is even viable
62 if 'atoms' not in data_dict:
63 raise RuntimeError('Magres file does not contain structure data')
65 # Allowed units handling. This is redundant for now but
66 # could turn out useful in the future
68 magres_units = {'Angstrom': ase.units.Ang}
70 # Lattice parameters?
71 if 'lattice' in data_dict['atoms']:
72 try:
73 u = dict(data_dict['atoms']['units'])['lattice']
74 except KeyError:
75 raise RuntimeError('No units detected in file for lattice')
76 u = magres_units[u]
77 cell = np.array(data_dict['atoms']['lattice'][0]) * u
78 pbc = True
79 else:
80 cell = None
81 pbc = False
83 # Now the atoms
84 symbols = []
85 positions = []
86 indices = []
87 labels = []
89 if 'atom' in data_dict['atoms']:
90 try:
91 u = dict(data_dict['atoms']['units'])['atom']
92 except KeyError:
93 raise RuntimeError('No units detected in file for atom positions')
94 u = magres_units[u]
95 # Now we have to account for the possibility of there being CASTEP
96 # 'custom' species amongst the symbols
97 custom_species = None
98 for a in data_dict['atoms']['atom']:
99 spec_custom = a['species'].split(':', 1)
100 if len(spec_custom) > 1 and custom_species is None:
101 # Add it to the custom info!
102 custom_species = list(symbols)
103 symbols.append(spec_custom[0])
104 positions.append(a['position'])
105 indices.append(a['index'])
106 labels.append(a['label'])
107 if custom_species is not None:
108 custom_species.append(a['species'])
110 atoms = Atoms(cell=cell, pbc=pbc, symbols=symbols, positions=positions)
112 # Add custom species if present
113 if custom_species is not None:
114 atoms.new_array('castep_custom_species', np.array(custom_species))
116 # Add the spacegroup, if present and recognizable
117 if 'symmetry' in data_dict['atoms']:
118 try:
119 spg = Spacegroup(data_dict['atoms']['symmetry'][0])
120 except SpacegroupNotFoundError:
121 # Not found
122 spg = Spacegroup(1) # Most generic one
123 atoms.info['spacegroup'] = spg
125 # Set up the rest of the properties as arrays
126 atoms.new_array('indices', np.array(indices))
127 atoms.new_array('labels', np.array(labels))
129 # Now for the magres specific stuff
130 li_list = list(zip(labels, indices))
132 def create_magres_array(name, order, block):
134 if order == 1:
135 u_arr = [None] * len(li_list)
136 elif order == 2:
137 u_arr = [[None] * (i + 1) for i in range(len(li_list))]
138 else:
139 raise ValueError(
140 'Invalid order value passed to create_magres_array'
141 )
143 for s in block:
144 # Find the atom index/indices
145 if order == 1:
146 # First find out which atom this is
147 at = (s['atom']['label'], s['atom']['index'])
148 try:
149 ai = li_list.index(at)
150 except ValueError:
151 raise RuntimeError('Invalid data in magres block')
152 # Then add the relevant quantity
153 u_arr[ai] = s[mn]
154 else:
155 at1 = (s['atom1']['label'], s['atom1']['index'])
156 at2 = (s['atom2']['label'], s['atom2']['index'])
157 ai1 = li_list.index(at1)
158 ai2 = li_list.index(at2)
159 # Sort them
160 ai1, ai2 = sorted((ai1, ai2), reverse=True)
161 u_arr[ai1][ai2] = s[mn]
163 if order == 1:
164 return np.array(u_arr)
165 else:
166 return np.array(u_arr, dtype=object)
168 if 'magres' in data_dict:
169 if 'units' in data_dict['magres']:
170 atoms.info['magres_units'] = dict(data_dict['magres']['units'])
171 for u in atoms.info['magres_units']:
172 # This bit to keep track of tags
173 u0 = u.split('_')[0]
175 if u0 not in _mprops:
176 raise RuntimeError('Invalid data in magres block')
178 mn, order = _mprops[u0]
180 if order > 0:
181 u_arr = create_magres_array(
182 mn, order, data_dict['magres'][u]
183 )
184 atoms.new_array(u, u_arr)
185 else:
186 # atoms.info['magres_data'] = atoms.info.get('magres_data',
187 # {})
188 # # We only take element 0 because for this sort of data
189 # # there should be only that
190 # atoms.info['magres_data'][u] = \
191 # data_dict['magres'][u][0][mn]
192 if atoms.calc is None:
193 calc = SinglePointDFTCalculator(atoms)
194 atoms.calc = calc
195 atoms.calc.results[u] = data_dict['magres'][u][0][mn]
197 if 'calculation' in data_dict:
198 atoms.info['magresblock_calculation'] = data_dict['calculation']
200 if include_unrecognised:
201 for b in data_dict:
202 if b not in block_parsers:
203 atoms.info['magresblock_' + b] = data_dict[b]
205 return atoms
208def tensor_string(tensor):
209 return ' '.join(' '.join(str(x) for x in xs) for xs in tensor)
212def write_magres(fd, image):
213 """
214 A writing function for magres files. Two steps: first data are arranged
215 into structures, then dumped to the actual file
216 """
218 image_data = {}
219 image_data['atoms'] = {'units': []}
220 # Contains units, lattice and each individual atom
221 if np.all(image.get_pbc()):
222 # Has lattice!
223 image_data['atoms']['units'].append(['lattice', 'Angstrom'])
224 image_data['atoms']['lattice'] = [image.get_cell()]
226 # Now for the atoms
227 if image.has('labels'):
228 labels = image.get_array('labels')
229 else:
230 labels = image.get_chemical_symbols()
232 if image.has('indices'):
233 indices = image.get_array('indices')
234 else:
235 indices = [labels[: i + 1].count(labels[i]) for i in range(len(labels))]
237 # Iterate over atoms
238 symbols = (
239 image.get_array('castep_custom_species')
240 if image.has('castep_custom_species')
241 else image.get_chemical_symbols()
242 )
244 atom_info = list(zip(symbols, image.get_positions()))
245 if len(atom_info) > 0:
246 image_data['atoms']['units'].append(['atom', 'Angstrom'])
247 image_data['atoms']['atom'] = []
249 for i, a in enumerate(atom_info):
250 image_data['atoms']['atom'].append(
251 {
252 'index': indices[i],
253 'position': a[1],
254 'species': a[0],
255 'label': labels[i],
256 }
257 )
259 # Spacegroup, if present
260 if 'spacegroup' in image.info:
261 image_data['atoms']['symmetry'] = [
262 image.info['spacegroup'].symbol.replace(' ', '')
263 ]
265 # Now go on to do the same for magres information
266 if 'magres_units' in image.info:
267 image_data['magres'] = {'units': []}
269 for u in image.info['magres_units']:
270 # Get the type
271 p = u.split('_')[0]
272 if p in _mprops:
273 image_data['magres']['units'].append(
274 [u, image.info['magres_units'][u]]
275 )
276 image_data['magres'][u] = []
277 mn, order = _mprops[p]
279 if order == 0:
280 # The case of susceptibility
281 tens = {mn: image.calc.results[u]}
282 image_data['magres'][u] = tens
283 else:
284 arr = image.get_array(u)
285 li_tab = zip(labels, indices)
286 for i, (lab, ind) in enumerate(li_tab):
287 if order == 2:
288 for j, (lab2, ind2) in enumerate(li_tab[: i + 1]):
289 if arr[i][j] is not None:
290 tens = {
291 mn: arr[i][j],
292 'atom1': {'label': lab, 'index': ind},
293 'atom2': {'label': lab2, 'index': ind2},
294 }
295 image_data['magres'][u].append(tens)
296 elif order == 1:
297 if arr[i] is not None:
298 tens = {
299 mn: arr[i],
300 'atom': {'label': lab, 'index': ind},
301 }
302 image_data['magres'][u].append(tens)
304 # Calculation block, if present
305 if 'magresblock_calculation' in image.info:
306 image_data['calculation'] = image.info['magresblock_calculation']
308 def write_units(data, out):
309 if 'units' in data:
310 for tag, units in data['units']:
311 out.append(f' units {tag} {units}')
313 def write_magres_block(data):
314 """
315 Write out a <magres> block from its dictionary representation
316 """
318 out = []
320 def nout(tag, tensor_name):
321 if tag in data:
322 out.append(
323 ' '.join([' ', tag, tensor_string(data[tag][tensor_name])])
324 )
326 def siout(tag, tensor_name):
327 if tag in data:
328 for atom_si in data[tag]:
329 out.append(
330 (' %s %s %d %s')
331 % (
332 tag,
333 atom_si['atom']['label'],
334 atom_si['atom']['index'],
335 tensor_string(atom_si[tensor_name]),
336 )
337 )
339 write_units(data, out)
341 nout('sus', 'S')
342 siout('ms', 'sigma')
344 siout('efg_local', 'V')
345 siout('efg_nonlocal', 'V')
346 siout('efg', 'V')
348 def sisiout(tag, tensor_name):
349 if tag in data:
350 for isc in data[tag]:
351 out.append(
352 (' %s %s %d %s %d %s')
353 % (
354 tag,
355 isc['atom1']['label'],
356 isc['atom1']['index'],
357 isc['atom2']['label'],
358 isc['atom2']['index'],
359 tensor_string(isc[tensor_name]),
360 )
361 )
363 sisiout('isc_fc', 'K')
364 sisiout('isc_orbital_p', 'K')
365 sisiout('isc_orbital_d', 'K')
366 sisiout('isc_spin', 'K')
367 sisiout('isc', 'K')
369 return '\n'.join(out)
371 def write_atoms_block(data):
372 out = []
374 write_units(data, out)
376 if 'lattice' in data:
377 for lat in data['lattice']:
378 out.append(f' lattice {tensor_string(lat)}')
380 if 'symmetry' in data:
381 for sym in data['symmetry']:
382 out.append(f' symmetry {sym}')
384 if 'atom' in data:
385 for a in data['atom']:
386 out.append(
387 (' atom %s %s %s %s')
388 % (
389 a['species'],
390 a['label'],
391 a['index'],
392 ' '.join(str(x) for x in a['position']),
393 )
394 )
396 return '\n'.join(out)
398 def write_generic_block(data):
399 out = []
401 for tag, data in data.items():
402 for value in data:
403 out.append('{} {}'.format(tag, ' '.join(str(x) for x in value)))
405 return '\n'.join(out)
407 # Using this to preserve order
408 block_writers = OrderedDict(
409 [
410 ('calculation', write_generic_block),
411 ('atoms', write_atoms_block),
412 ('magres', write_magres_block),
413 ]
414 )
416 # First, write the header
417 fd.write('#$magres-abinitio-v1.0\n')
418 fd.write('# Generated by the Atomic Simulation Environment library\n')
420 for b in block_writers:
421 if b in image_data:
422 fd.write(f'[{b}]\n')
423 fd.write(block_writers[b](image_data[b]))
424 fd.write(f'\n[/{b}]\n')
426 # Now on to check for any non-standard blocks...
427 for i in image.info:
428 if '_' in i:
429 ismag, b = i.split('_', 1)
430 if ismag == 'magresblock' and b not in block_writers:
431 fd.write(f'[{b}]\n')
432 fd.write(image.info[i])
433 fd.write(f'[/{b}]\n')