Coverage for ase/io/extxyz.py: 84.93%
531 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"""
2Extended XYZ support
4Read/write files in "extended" XYZ format, storing additional
5per-configuration information as key-value pairs on the XYZ
6comment line, and additional per-atom properties as extra columns.
8Contributed by James Kermode <james.kermode@gmail.com>
9"""
11import json
12import numbers
13import re
14import warnings
15from collections.abc import Iterator
16from io import StringIO, UnsupportedOperation
17from typing import TextIO
19import numpy as np
21from ase.atoms import Atoms
22from ase.calculators.calculator import all_properties
23from ase.calculators.singlepoint import SinglePointCalculator
24from ase.constraints import FixAtoms, FixCartesian
25from ase.io.formats import index2range
26from ase.io.utils import ImageChunk, ImageIterator, validate_comment_line
27from ase.outputs import ArrayProperty, all_outputs
28from ase.spacegroup.spacegroup import Spacegroup
29from ase.stress import voigt_6_to_full_3x3_stress
30from ase.utils import reader, writer
32__all__ = ['read_xyz', 'write_xyz', 'iread_xyz']
34PROPERTY_NAME_MAP = {
35 'positions': 'pos',
36 'numbers': 'Z',
37 'charges': 'charge',
38 'symbols': 'species',
39}
41REV_PROPERTY_NAME_MAP = dict(
42 zip(PROPERTY_NAME_MAP.values(), PROPERTY_NAME_MAP.keys())
43)
45KEY_QUOTED_VALUE = re.compile(
46 r'([A-Za-z_]+[A-Za-z0-9_-]*)' + r'\s*=\s*["\{\}]([^"\{\}]+)["\{\}]\s*'
47)
48KEY_VALUE = re.compile(r'([A-Za-z_]+[A-Za-z0-9_]*)\s*=' + r'\s*([^\s]+)\s*')
49KEY_RE = re.compile(r'([A-Za-z_]+[A-Za-z0-9_-]*)\s*')
51UNPROCESSED_KEYS = {'uid'}
53SPECIAL_3_3_KEYS = {'Lattice', 'virial', 'stress'}
55# Determine 'per-atom' and 'per-config' based on all_outputs shape,
56# but filter for things in all_properties because that's what
57# SinglePointCalculator accepts
58per_atom_properties = []
59per_config_properties = []
60for key, val in all_outputs.items():
61 if key not in all_properties:
62 continue
63 if isinstance(val, ArrayProperty) and val.shapespec[0] == 'natoms':
64 per_atom_properties.append(key)
65 else:
66 per_config_properties.append(key)
69def key_val_str_to_dict(string, sep=None):
70 """
71 Parse an xyz properties string in a key=value and return a dict with
72 various values parsed to native types.
74 Accepts brackets or quotes to delimit values. Parses integers, floats
75 booleans and arrays thereof. Arrays with 9 values whose name is listed
76 in SPECIAL_3_3_KEYS are converted to 3x3 arrays with Fortran ordering.
78 If sep is None, string will split on whitespace, otherwise will split
79 key value pairs with the given separator.
81 """
82 # store the closing delimiters to match opening ones
83 delimiters = {"'": "'", '"': '"', '{': '}', '[': ']'}
85 # Make pairs and process afterwards
86 kv_pairs = [
87 [[]]
88 ] # List of characters for each entry, add a new list for new value
89 cur_delimiter = None # push and pop closing delimiters
90 escaped = False # add escaped sequences verbatim
92 # parse character-by-character unless someone can do nested brackets
93 # and escape sequences in a regex
94 for char in string.strip():
95 if escaped: # bypass everything if escaped
96 kv_pairs[-1][-1].append(char)
97 escaped = False
98 elif char == '\\': # escape the next thing
99 escaped = True
100 elif cur_delimiter: # inside brackets
101 if char == cur_delimiter: # found matching delimiter
102 cur_delimiter = None
103 else:
104 kv_pairs[-1][-1].append(char) # inside quotes, add verbatim
105 elif char in delimiters:
106 cur_delimiter = delimiters[char] # brackets or quotes
107 elif (sep is None and char.isspace()) or char == sep:
108 if kv_pairs == [[[]]]: # empty, beginning of string
109 continue
110 elif kv_pairs[-1][-1] == []:
111 continue
112 else:
113 kv_pairs.append([[]])
114 elif char == '=':
115 if kv_pairs[-1] == [[]]:
116 del kv_pairs[-1]
117 kv_pairs[-1].append([]) # value
118 else:
119 kv_pairs[-1][-1].append(char)
121 kv_dict = {}
123 for kv_pair in kv_pairs:
124 if len(kv_pair) == 0: # empty line
125 continue
126 elif len(kv_pair) == 1: # default to True
127 key, value = ''.join(kv_pair[0]), 'T'
128 else: # Smush anything else with kv-splitter '=' between them
129 key, value = (
130 ''.join(kv_pair[0]),
131 '='.join(''.join(x) for x in kv_pair[1:]),
132 )
134 if key.lower() not in UNPROCESSED_KEYS:
135 # Try to convert to (arrays of) floats, ints
136 split_value = re.findall(r'[^\s,]+', value)
137 try:
138 try:
139 numvalue = np.array(split_value, dtype=int)
140 except (ValueError, OverflowError):
141 # don't catch errors here so it falls through to bool
142 numvalue = np.array(split_value, dtype=float)
143 if len(numvalue) == 1:
144 numvalue = numvalue[0] # Only one number
145 value = numvalue
146 except (ValueError, OverflowError):
147 pass # value is unchanged
149 # convert special 3x3 matrices
150 if key in SPECIAL_3_3_KEYS:
151 if not isinstance(value, np.ndarray) or value.shape != (9,):
152 raise ValueError(
153 'Got info item {}, expecting special 3x3 '
154 'matrix, but value is not in the form of '
155 'a 9-long numerical vector'.format(key)
156 )
157 value = np.array(value).reshape((3, 3), order='F')
159 # parse special strings as boolean or JSON
160 if isinstance(value, str):
161 # Parse boolean values:
162 # T or [tT]rue or TRUE -> True
163 # F or [fF]alse or FALSE -> False
164 # For list: 'T T F' -> [True, True, False]
165 # Cannot use `.lower()` to reduce `str_to_bool` mapping because
166 # 't'/'f' not accepted
167 str_to_bool = {
168 'T': True,
169 'F': False,
170 'true': True,
171 'false': False,
172 'True': True,
173 'False': False,
174 'TRUE': True,
175 'FALSE': False,
176 }
177 try:
178 boolvalue = [
179 str_to_bool[vpart]
180 for vpart in re.findall(r'[^\s,]+', value)
181 ]
183 if len(boolvalue) == 1:
184 value = boolvalue[0]
185 else:
186 value = boolvalue
187 except KeyError:
188 # Try to parse JSON
189 if value.startswith('_JSON '):
190 d = json.loads(value.replace('_JSON ', '', 1))
191 value = np.array(d)
192 if value.dtype.kind not in ['i', 'f', 'b']:
193 value = d
195 kv_dict[key] = value
197 return kv_dict
200def key_val_str_to_dict_regex(s):
201 """
202 Parse strings in the form 'key1=value1 key2="quoted value"'
203 """
204 d = {}
205 s = s.strip()
206 while True:
207 # Match quoted string first, then fall through to plain key=value
208 m = KEY_QUOTED_VALUE.match(s)
209 if m is None:
210 m = KEY_VALUE.match(s)
211 if m is not None:
212 s = KEY_VALUE.sub('', s, 1)
213 else:
214 # Just a key with no value
215 m = KEY_RE.match(s)
216 if m is not None:
217 s = KEY_RE.sub('', s, 1)
218 else:
219 s = KEY_QUOTED_VALUE.sub('', s, 1)
221 if m is None:
222 break # No more matches
224 key = m.group(1)
225 try:
226 value = m.group(2)
227 except IndexError:
228 # default value is 'T' (True)
229 value = 'T'
231 if key.lower() not in UNPROCESSED_KEYS:
232 # Try to convert to (arrays of) floats, ints
233 try:
234 numvalue = []
235 for x in value.split():
236 if x.find('.') == -1:
237 numvalue.append(int(float(x)))
238 else:
239 numvalue.append(float(x))
240 if len(numvalue) == 1:
241 numvalue = numvalue[0] # Only one number
242 elif len(numvalue) == 9:
243 # special case: 3x3 matrix, fortran ordering
244 numvalue = np.array(numvalue).reshape((3, 3), order='F')
245 else:
246 numvalue = np.array(numvalue) # vector
247 value = numvalue
248 except (ValueError, OverflowError):
249 pass
251 # Parse boolean values: 'T' -> True, 'F' -> False,
252 # 'T T F' -> [True, True, False]
253 if isinstance(value, str):
254 str_to_bool = {'T': True, 'F': False}
256 if len(value.split()) > 1:
257 if all(x in str_to_bool for x in value.split()):
258 value = [str_to_bool[x] for x in value.split()]
259 elif value in str_to_bool:
260 value = str_to_bool[value]
262 d[key] = value
264 return d
267def escape(string):
268 if (
269 ' ' in string
270 or '"' in string
271 or "'" in string
272 or '{' in string
273 or '}' in string
274 or '[' in string
275 or ']' in string
276 ):
277 string = string.replace('"', '\\"')
278 string = f'"{string}"'
279 return string
282def key_val_dict_to_str(dct, sep=' '):
283 """
284 Convert atoms.info dictionary to extended XYZ string representation
285 """
287 def array_to_string(key, val):
288 # some ndarrays are special (special 3x3 keys, and scalars/vectors of
289 # numbers or bools), handle them here
290 if key in SPECIAL_3_3_KEYS:
291 # special 3x3 matrix, flatten in Fortran order
292 val = val.reshape(val.size, order='F')
293 if val.dtype.kind in ['i', 'f', 'b']:
294 # numerical or bool scalars/vectors are special, for backwards
295 # compat.
296 if len(val.shape) == 0:
297 # scalar
298 val = str(known_types_to_str(val))
299 elif len(val.shape) == 1:
300 # vector
301 val = ' '.join(str(known_types_to_str(v)) for v in val)
302 return val
304 def known_types_to_str(val):
305 if isinstance(val, (bool, np.bool_)):
306 return 'T' if val else 'F'
307 elif isinstance(val, numbers.Real):
308 return f'{val}'
309 elif isinstance(val, Spacegroup):
310 return val.symbol
311 else:
312 return val
314 if len(dct) == 0:
315 return ''
317 string = ''
318 for key in dct:
319 val = dct[key]
321 if isinstance(val, np.ndarray):
322 val = array_to_string(key, val)
323 else:
324 # convert any known types to string
325 val = known_types_to_str(val)
327 if val is not None and not isinstance(val, str):
328 # what's left is an object, try using JSON
329 if isinstance(val, np.ndarray):
330 val = val.tolist()
331 try:
332 val = '_JSON ' + json.dumps(val)
333 # if this fails, let give up
334 except TypeError:
335 warnings.warn('Skipping unhashable information {}'.format(key))
336 continue
338 key = escape(key) # escape and quote key
339 eq = '='
340 # Should this really be setting empty value that's going to be
341 # interpreted as bool True?
342 if val is None:
343 val = ''
344 eq = ''
345 val = escape(val) # escape and quote val
347 string += f'{key}{eq}{val}{sep}'
349 return string.strip()
352def parse_properties(prop_str):
353 """
354 Parse extended XYZ properties format string
356 Format is "[NAME:TYPE:NCOLS]...]", e.g. "species:S:1:pos:R:3".
357 NAME is the name of the property.
358 TYPE is one of R, I, S, L for real, integer, string and logical.
359 NCOLS is number of columns for that property.
360 """
362 properties = {}
363 properties_list = []
364 dtypes = []
365 converters = []
367 fields = prop_str.split(':')
369 def parse_bool(x):
370 """
371 Parse bool to string
372 """
373 return {'T': True, 'F': False, 'True': True, 'False': False}.get(x)
375 fmt_map = {
376 'R': ('d', float),
377 'I': ('i', int),
378 'S': (object, str),
379 'L': ('bool', parse_bool),
380 }
382 for name, ptype, cols in zip(
383 fields[::3], fields[1::3], [int(x) for x in fields[2::3]]
384 ):
385 if ptype not in ('R', 'I', 'S', 'L'):
386 raise ValueError('Unknown property type: ' + ptype)
387 ase_name = REV_PROPERTY_NAME_MAP.get(name, name)
389 dtype, converter = fmt_map[ptype]
390 if cols == 1:
391 dtypes.append((name, dtype))
392 converters.append(converter)
393 else:
394 for c in range(cols):
395 dtypes.append((name + str(c), dtype))
396 converters.append(converter)
398 properties[name] = (ase_name, cols)
399 properties_list.append(name)
401 dtype = np.dtype(dtypes)
402 return properties, properties_list, dtype, converters
405def _read_xyz_frame(
406 lines, natoms, properties_parser=key_val_str_to_dict, nvec=0
407):
408 # comment line
409 line = next(lines).strip()
410 if nvec > 0:
411 info = {'comment': line}
412 else:
413 info = properties_parser(line) if line else {}
415 pbc = None
416 if 'pbc' in info:
417 pbc = info.pop('pbc')
418 elif 'Lattice' in info:
419 # default pbc for extxyz file containing Lattice
420 # is True in all directions
421 pbc = [True, True, True]
422 elif nvec > 0:
423 # cell information given as pseudo-Atoms
424 pbc = [False, False, False]
426 cell = None
427 if 'Lattice' in info:
428 # NB: ASE cell is transpose of extended XYZ lattice
429 cell = info['Lattice'].T
430 del info['Lattice']
431 elif nvec > 0:
432 # cell information given as pseudo-Atoms
433 cell = np.zeros((3, 3))
435 if 'Properties' not in info:
436 # Default set of properties is atomic symbols and positions only
437 info['Properties'] = 'species:S:1:pos:R:3'
438 properties, names, dtype, convs = parse_properties(info['Properties'])
439 del info['Properties']
441 data = []
442 for _ in range(natoms):
443 try:
444 line = next(lines)
445 except StopIteration:
446 raise XYZError(
447 'ase.io.extxyz: Frame has {} atoms, expected {}'.format(
448 len(data), natoms
449 )
450 )
451 vals = line.split()
452 row = tuple(conv(val) for conv, val in zip(convs, vals))
453 data.append(row)
455 try:
456 data = np.array(data, dtype)
457 except TypeError:
458 raise XYZError(
459 'Badly formatted data or end of file reached before end of frame'
460 )
462 # Read VEC entries if present
463 if nvec > 0:
464 for ln in range(nvec):
465 try:
466 line = next(lines)
467 except StopIteration:
468 raise XYZError(
469 'ase.io.adfxyz: Frame has {} cell vectors, '
470 'expected {}'.format(len(cell), nvec)
471 )
472 entry = line.split()
474 if not entry[0].startswith('VEC'):
475 raise XYZError(f'Expected cell vector, got {entry[0]}')
477 try:
478 n = int(entry[0][3:])
479 except ValueError as e:
480 raise XYZError(
481 'Expected VEC{}, got VEC{}'.format(ln + 1, entry[0][3:])
482 ) from e
483 if n != ln + 1:
484 raise XYZError('Expected VEC{}, got VEC{}'.format(ln + 1, n))
486 cell[ln] = np.array([float(x) for x in entry[1:]])
487 pbc[ln] = True
488 if nvec != pbc.count(True):
489 raise XYZError('Problem with number of cell vectors')
490 pbc = tuple(pbc)
492 arrays = {}
493 for name in names:
494 ase_name, cols = properties[name]
495 if cols == 1:
496 value = data[name]
497 else:
498 value = np.vstack([data[name + str(c)] for c in range(cols)]).T
499 arrays[ase_name] = value
501 numbers = arrays.pop('numbers', None)
502 symbols = arrays.pop('symbols', None)
504 if symbols is not None:
505 symbols = [s.capitalize() for s in symbols]
507 atoms = Atoms(
508 numbers if numbers is not None else symbols,
509 positions=arrays.pop('positions', None),
510 charges=arrays.pop('initial_charges', None),
511 cell=cell,
512 pbc=pbc,
513 info=info,
514 )
516 # Read and set constraints
517 if 'move_mask' in arrays:
518 move_mask = arrays.pop('move_mask').astype(bool)
519 if properties['move_mask'][1] == 3:
520 cons = []
521 for a in range(natoms):
522 cons.append(FixCartesian(a, mask=~move_mask[a, :]))
523 atoms.set_constraint(cons)
524 elif properties['move_mask'][1] == 1:
525 atoms.set_constraint(FixAtoms(mask=~move_mask))
526 else:
527 raise XYZError('Not implemented constraint')
529 set_calc_and_arrays(atoms, arrays)
530 return atoms
533def set_calc_and_arrays(atoms, arrays):
534 results = {}
536 for name, array in arrays.items():
537 if name in all_properties:
538 results[name] = array
539 else:
540 # store non-standard items in atoms.arrays
541 atoms.new_array(name, array)
543 for key in list(atoms.info):
544 if key in per_config_properties:
545 results[key] = atoms.info.pop(key)
546 # special case for stress- convert to Voigt 6-element form
547 if key == 'stress' and results[key].shape == (3, 3):
548 stress = results[key]
549 stress = np.array(
550 [
551 stress[0, 0],
552 stress[1, 1],
553 stress[2, 2],
554 stress[1, 2],
555 stress[0, 2],
556 stress[0, 1],
557 ]
558 )
559 results[key] = stress
561 if results:
562 atoms.calc = SinglePointCalculator(atoms, **results)
565class XYZError(IOError):
566 pass
569class XYZChunk(ImageChunk):
570 def __init__(self, fd: TextIO, pos: int) -> None:
571 self.fd = fd
572 self.pos = pos
574 def build(self, **kwargs) -> Atoms:
575 """Convert unprocessed chunk into Atoms."""
576 self.fd.seek(self.pos)
577 natoms = int(self.fd.readline().strip()[0])
578 lines = [self.fd.readline() for _ in range(1 + natoms)]
579 return _read_xyz_frame(iter(lines), natoms, **kwargs)
582def ixyzchunks(fd: TextIO) -> Iterator[XYZChunk]:
583 """Yield unprocessed chunks (header, lines) for each xyz image."""
584 pos = fd.tell()
585 while line := fd.readline():
586 natoms = int(line.strip()[0])
587 _ = [fd.readline() for _ in range(1 + natoms)]
588 yield XYZChunk(fd, pos)
589 pos = fd.tell()
592iread_xyz = ImageIterator(ixyzchunks)
595@reader
596def read_xyz(fileobj, index=-1, properties_parser=key_val_str_to_dict):
597 r"""
598 Read from a file in Extended XYZ format
600 index is the frame to read, default is last frame (index=-1).
601 properties_parser is the parse to use when converting the properties line
602 to a dictionary, ``extxyz.key_val_str_to_dict`` is the default and can
603 deal with most use cases, ``extxyz.key_val_str_to_dict_regex`` is slightly
604 faster but has fewer features.
606 Extended XYZ format is an enhanced version of the `basic XYZ format
607 <http://en.wikipedia.org/wiki/XYZ_file_format>`_ that allows extra
608 columns to be present in the file for additonal per-atom properties as
609 well as standardising the format of the comment line to include the
610 cell lattice and other per-frame parameters.
612 It's easiest to describe the format with an example. Here is a
613 standard XYZ file containing a bulk cubic 8 atom silicon cell ::
615 8
616 Cubic bulk silicon cell
617 Si 0.00000000 0.00000000 0.00000000
618 Si 1.36000000 1.36000000 1.36000000
619 Si 2.72000000 2.72000000 0.00000000
620 Si 4.08000000 4.08000000 1.36000000
621 Si 2.72000000 0.00000000 2.72000000
622 Si 4.08000000 1.36000000 4.08000000
623 Si 0.00000000 2.72000000 2.72000000
624 Si 1.36000000 4.08000000 4.08000000
626 The first line is the number of atoms, followed by a comment and
627 then one line per atom, giving the element symbol and cartesian
628 x y, and z coordinates in Angstroms.
630 Here's the same configuration in extended XYZ format ::
632 8
633 Lattice="5.44 0.0 0.0 0.0 5.44 0.0 0.0 0.0 5.44" Properties=species:S:1:pos:R:3 Time=0.0
634 Si 0.00000000 0.00000000 0.00000000
635 Si 1.36000000 1.36000000 1.36000000
636 Si 2.72000000 2.72000000 0.00000000
637 Si 4.08000000 4.08000000 1.36000000
638 Si 2.72000000 0.00000000 2.72000000
639 Si 4.08000000 1.36000000 4.08000000
640 Si 0.00000000 2.72000000 2.72000000
641 Si 1.36000000 4.08000000 4.08000000
643 In extended XYZ format, the comment line is replaced by a series of
644 key/value pairs. The keys should be strings and values can be
645 integers, reals, logicals (denoted by `T` and `F` for true and false)
646 or strings. Quotes are required if a value contains any spaces (like
647 `Lattice` above). There are two mandatory parameters that any
648 extended XYZ: `Lattice` and `Properties`. Other parameters --
649 e.g. `Time` in the example above --- can be added to the parameter line
650 as needed.
652 `Lattice` is a Cartesian 3x3 matrix representation of the cell
653 vectors, with each vector stored as a column and the 9 values listed in
654 Fortran column-major order, i.e. in the form ::
656 Lattice="R1x R1y R1z R2x R2y R2z R3x R3y R3z"
658 where `R1x R1y R1z` are the Cartesian x-, y- and z-components of the
659 first lattice vector (:math:`\mathbf{a}`), `R2x R2y R2z` those of the second
660 lattice vector (:math:`\mathbf{b}`) and `R3x R3y R3z` those of the
661 third lattice vector (:math:`\mathbf{c}`).
663 The list of properties in the file is described by the `Properties`
664 parameter, which should take the form of a series of colon separated
665 triplets giving the name, format (`R` for real, `I` for integer) and
666 number of columns of each property. For example::
668 Properties="species:S:1:pos:R:3:vel:R:3:select:I:1"
670 indicates the first column represents atomic species, the next three
671 columns represent atomic positions, the next three velcoities, and the
672 last is an single integer called `select`. With this property
673 definition, the line ::
675 Si 4.08000000 4.08000000 1.36000000 0.00000000 0.00000000 0.00000000 1
677 would describe a silicon atom at position (4.08,4.08,1.36) with zero
678 velocity and the `select` property set to 1.
680 The property names `pos`, `Z`, `mass`, and `charge` map to ASE
681 :attr:`ase.atoms.Atoms.arrays` entries named
682 `positions`, `numbers`, `masses` and `charges` respectively.
684 Additional key-value pairs in the comment line are parsed into the
685 :attr:`ase.Atoms.atoms.info` dictionary, with the following conventions
687 - Values can be quoted with `""`, `''`, `[]` or `{}` (the latter are
688 included to ease command-line usage as the `{}` are not treated
689 specially by the shell)
690 - Quotes within keys or values can be escaped with `\"`.
691 - Keys with special names `stress` or `virial` are treated as 3x3 matrices
692 in Fortran order, as for `Lattice` above.
693 - Otherwise, values with multiple elements are treated as 1D arrays, first
694 assuming integer format and falling back to float if conversion is
695 unsuccessful.
696 - A missing value defaults to `True`, e.g. the comment line
697 `"cutoff=3.4 have_energy"` leads to
698 `{'cutoff': 3.4, 'have_energy': True}` in `atoms.info`.
699 - Value strings starting with `"_JSON"` are interpreted as JSON content;
700 similarly, when writing, anything which does not match the criteria above
701 is serialised as JSON.
703 The extended XYZ format is also supported by the
704 the `Ovito <https://www.ovito.org>`_ visualisation tool.
705 """ # noqa: E501
707 if not isinstance(index, int) and not isinstance(index, slice):
708 raise TypeError('Index argument is neither slice nor integer!')
710 # If possible, build a partial index up to the last frame required
711 last_frame = None
712 if isinstance(index, int) and index >= 0:
713 last_frame = index
714 elif isinstance(index, slice):
715 if index.stop is not None and index.stop >= 0:
716 last_frame = index.stop
718 # scan through file to find where the frames start
719 try:
720 fileobj.seek(0)
721 except UnsupportedOperation:
722 fileobj = StringIO(fileobj.read())
723 fileobj.seek(0)
724 frames = []
725 while True:
726 frame_pos = fileobj.tell()
727 line = fileobj.readline()
728 if line.strip() == '':
729 break
730 try:
731 natoms = int(line)
732 except ValueError as err:
733 raise XYZError(
734 'ase.io.extxyz: Expected xyz header but got: {}'.format(err)
735 )
736 fileobj.readline() # read comment line
737 for _ in range(natoms):
738 fileobj.readline()
739 # check for VEC
740 nvec = 0
741 while True:
742 lastPos = fileobj.tell()
743 line = fileobj.readline()
744 if line.lstrip().startswith('VEC'):
745 nvec += 1
746 if nvec > 3:
747 raise XYZError('ase.io.extxyz: More than 3 VECX entries')
748 else:
749 fileobj.seek(lastPos)
750 break
751 frames.append((frame_pos, natoms, nvec))
752 if last_frame is not None and len(frames) > last_frame:
753 break
755 trbl = index2range(index, len(frames))
757 for index in trbl:
758 frame_pos, natoms, nvec = frames[index]
759 fileobj.seek(frame_pos)
760 # check for consistency with frame index table
761 frame_natoms = int(fileobj.readline())
762 if frame_natoms != natoms:
763 msg = f'ase.io.extxyz: Frame has {frame_natoms}, expected {natoms}'
764 raise XYZError(msg)
765 yield _read_xyz_frame(fileobj, natoms, properties_parser, nvec)
768def output_column_format(atoms, columns, arrays, write_info=True):
769 """
770 Helper function to build extended XYZ comment line
771 """
772 fmt_map = {
773 'd': ('R', '%16.8f'),
774 'f': ('R', '%16.8f'),
775 'i': ('I', '%8d'),
776 'O': ('S', '%s'),
777 'S': ('S', '%s'),
778 'U': ('S', '%-2s'),
779 'b': ('L', ' %.1s'),
780 }
782 # NB: Lattice is stored as tranpose of ASE cell,
783 # with Fortran array ordering
784 lattice_str = (
785 'Lattice="'
786 + ' '.join([str(x) for x in np.reshape(atoms.cell.T, 9, order='F')])
787 + '"'
788 )
790 property_names = []
791 property_types = []
792 property_ncols = []
793 dtypes = []
794 formats = []
796 for column in columns:
797 array = arrays[column]
798 dtype = array.dtype
800 property_name = PROPERTY_NAME_MAP.get(column, column)
801 property_type, fmt = fmt_map[dtype.kind]
802 property_names.append(property_name)
803 property_types.append(property_type)
805 if len(array.shape) == 1 or (
806 len(array.shape) == 2 and array.shape[1] == 1
807 ):
808 ncol = 1
809 dtypes.append((column, dtype))
810 else:
811 ncol = array.shape[1]
812 for c in range(ncol):
813 dtypes.append((column + str(c), dtype))
815 formats.extend([fmt] * ncol)
816 property_ncols.append(ncol)
818 props_str = ':'.join(
819 [
820 ':'.join(x)
821 for x in zip(
822 property_names,
823 property_types,
824 [str(nc) for nc in property_ncols],
825 )
826 ]
827 )
829 comment_str = ''
830 if atoms.cell.any():
831 comment_str += lattice_str + ' '
832 comment_str += f'Properties={props_str}'
834 info = {}
835 if write_info:
836 info.update(atoms.info)
837 info['pbc'] = atoms.get_pbc() # always save periodic boundary conditions
838 comment_str += ' ' + key_val_dict_to_str(info)
840 dtype = np.dtype(dtypes)
841 fmt = ' '.join(formats) + '\n'
843 return comment_str, property_ncols, dtype, fmt
846def _make_move_mask(atoms: Atoms) -> np.ndarray:
847 natoms = len(atoms)
848 cnstr = atoms.constraints
849 cnstr = [_ for _ in cnstr if isinstance(_, (FixAtoms, FixCartesian))]
850 if any(isinstance(_, FixCartesian) for _ in cnstr):
851 move_mask = np.ones((natoms, 3), dtype=bool)
852 else:
853 move_mask = np.ones((natoms,), dtype=bool)
854 for c0 in cnstr:
855 if isinstance(c0, FixAtoms):
856 move_mask[c0.index] = False
857 elif isinstance(c0, FixCartesian):
858 # The `False` elements of `move_mask` should be kept.
859 move_mask[c0.index] = ~c0.mask & move_mask[c0.index]
860 return move_mask
863@writer
864def write_xyz(
865 fileobj,
866 images,
867 comment='',
868 columns=None,
869 write_info=True,
870 write_results=True,
871 plain=False,
872 vec_cell=False,
873):
874 """
875 Write output in extended XYZ format
877 ``images`` may be Atoms or any Iterable[Atoms].
879 Optionally, specify which columns (arrays) to include in output,
880 whether to write the contents of the `atoms.info` dict to the
881 XYZ comment line (default is True), the results of any
882 calculator attached to this Atoms. The `plain` argument
883 can be used to write a simple XYZ file with no additional information.
884 `vec_cell` can be used to write the cell vectors as additional
885 pseudo-atoms.
887 See documentation for :func:`read_xyz()` for further details of the extended
888 XYZ file format.
889 """
891 if hasattr(images, 'get_positions'):
892 images = [images]
894 for atoms in images:
895 natoms = len(atoms)
897 if write_results:
898 calculator = atoms.calc
899 atoms = atoms.copy()
901 save_calc_results(atoms, calculator, calc_prefix='')
903 if atoms.info.get('stress', np.array([])).shape == (6,):
904 atoms.info['stress'] = voigt_6_to_full_3x3_stress(
905 atoms.info['stress']
906 )
908 if columns is None:
909 fr_cols = ['symbols', 'positions', 'move_mask'] + [
910 key
911 for key in atoms.arrays
912 if key
913 not in ['symbols', 'positions', 'numbers', 'species', 'pos']
914 ]
915 else:
916 fr_cols = columns[:]
918 if vec_cell:
919 plain = True
921 if plain:
922 fr_cols = ['symbols', 'positions']
923 write_info = False
924 write_results = False
926 # Move symbols and positions to first two properties
927 if 'symbols' in fr_cols:
928 i = fr_cols.index('symbols')
929 fr_cols[0], fr_cols[i] = fr_cols[i], fr_cols[0]
931 if 'positions' in fr_cols:
932 i = fr_cols.index('positions')
933 fr_cols[1], fr_cols[i] = fr_cols[i], fr_cols[1]
935 # Check first column "looks like" atomic symbols
936 if fr_cols[0] in atoms.arrays:
937 symbols = atoms.arrays[fr_cols[0]]
938 else:
939 symbols = [*atoms.symbols]
941 if natoms > 0 and not isinstance(symbols[0], str):
942 raise ValueError('First column must be symbols-like')
944 # Check second column "looks like" atomic positions
945 pos = atoms.arrays[fr_cols[1]]
946 if pos.shape != (natoms, 3) or pos.dtype.kind != 'f':
947 raise ValueError('Second column must be position-like')
949 # if vec_cell add cell information as pseudo-atoms
950 if vec_cell:
951 nPBC = 0
952 for i, b in enumerate(atoms.pbc):
953 if not b:
954 continue
955 nPBC += 1
956 symbols.append('VEC' + str(nPBC))
957 pos = np.vstack((pos, atoms.cell[i]))
958 # add to natoms
959 natoms += nPBC
960 if pos.shape != (natoms, 3) or pos.dtype.kind != 'f':
961 raise ValueError('Pseudo Atoms containing cell have bad coords')
963 # Move mask
964 if 'move_mask' in fr_cols:
965 move_mask = _make_move_mask(atoms)
966 if np.all(move_mask):
967 fr_cols.remove('move_mask')
969 # Collect data to be written out
970 arrays = {}
971 for column in fr_cols:
972 if column == 'positions':
973 arrays[column] = pos
974 elif column in atoms.arrays:
975 arrays[column] = atoms.arrays[column]
976 elif column == 'symbols':
977 arrays[column] = np.array(symbols)
978 elif column == 'move_mask':
979 arrays[column] = move_mask
980 else:
981 raise ValueError(f'Missing array "{column}"')
983 comm, ncols, dtype, fmt = output_column_format(
984 atoms, fr_cols, arrays, write_info
985 )
987 if plain or comment != '':
988 # override key/value pairs with user-speficied comment string
989 comm = validate_comment_line(comment)
991 # Pack fr_cols into record array
992 data = np.zeros(natoms, dtype)
993 for column, ncol in zip(fr_cols, ncols):
994 value = arrays[column]
995 if ncol == 1:
996 data[column] = np.squeeze(value)
997 else:
998 for c in range(ncol):
999 data[column + str(c)] = value[:, c]
1001 nat = natoms
1002 if vec_cell:
1003 nat -= nPBC
1004 # Write the output
1005 fileobj.write('%d\n' % nat)
1006 fileobj.write(f'{comm}\n')
1007 for i in range(natoms):
1008 fileobj.write(fmt % tuple(data[i]))
1011def save_calc_results(
1012 atoms, calc=None, calc_prefix=None, remove_atoms_calc=False, force=False
1013):
1014 """Update information in atoms from results in a calculator
1016 Args:
1017 atoms (ase.atoms.Atoms): Atoms object, modified in place
1018 calc (ase.calculators.Calculator, optional): calculator to take results
1019 from. Defaults to :attr:`atoms.calc`
1020 calc_prefix (str, optional): String to prefix to results names
1021 in :attr:`atoms.arrays` and :attr:`atoms.info`. Defaults to
1022 calculator class name
1023 remove_atoms_calc (bool): remove the calculator from the `atoms`
1024 object after saving its results. Defaults to `False`, ignored if
1025 `calc` is passed in
1026 force (bool, optional): overwrite existing fields with same name,
1027 default False
1028 """
1029 if calc is None:
1030 calc_use = atoms.calc
1031 else:
1032 calc_use = calc
1034 if calc_use is None:
1035 return None, None
1037 if calc_prefix is None:
1038 calc_prefix = calc_use.__class__.__name__ + '_'
1040 per_config_results = {}
1041 per_atom_results = {}
1042 for prop, value in calc_use.results.items():
1043 if prop in per_config_properties:
1044 per_config_results[calc_prefix + prop] = value
1045 elif prop in per_atom_properties:
1046 per_atom_results[calc_prefix + prop] = value
1048 if not force:
1049 if any(key in atoms.info for key in per_config_results):
1050 raise KeyError('key from calculator already exists in atoms.info')
1051 if any(key in atoms.arrays for key in per_atom_results):
1052 raise KeyError('key from calculator already exists in atoms.arrays')
1054 atoms.info.update(per_config_results)
1055 atoms.arrays.update(per_atom_results)
1057 if remove_atoms_calc and calc is None:
1058 atoms.calc = None
1061# create aliases for read/write functions
1062read_extxyz = read_xyz
1063write_extxyz = write_xyz