Coverage for ase/io/xyz.py: 100.00%

27 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1"""Reference implementation of reader and writer for standard XYZ files. 

2 

3See https://en.wikipedia.org/wiki/XYZ_file_format 

4 

5Note that the .xyz files are handled by the extxyz module by default. 

6""" 

7 

8from ase.atoms import Atoms 

9from ase.io.utils import validate_comment_line 

10 

11 

12def read_xyz(fileobj, index): 

13 # This function reads first all atoms and then yields based on the index. 

14 # Perfomance could be improved, but this serves as a simple reference. 

15 # It'd require more code to estimate the total number of images 

16 # without reading through the whole file (note: the number of atoms 

17 # can differ for every image). 

18 lines = fileobj.readlines() 

19 images = [] 

20 while len(lines) > 0: 

21 symbols = [] 

22 positions = [] 

23 natoms = int(lines.pop(0)) 

24 lines.pop(0) # Comment line; ignored 

25 for _ in range(natoms): 

26 line = lines.pop(0) 

27 symbol, x, y, z = line.split()[:4] 

28 symbol = symbol.lower().capitalize() 

29 symbols.append(symbol) 

30 positions.append([float(x), float(y), float(z)]) 

31 images.append(Atoms(symbols=symbols, positions=positions)) 

32 yield from images[index] 

33 

34 

35def write_xyz(fileobj, images, comment='', fmt='%22.15f'): 

36 comment = validate_comment_line(comment) 

37 

38 for atoms in images: 

39 natoms = len(atoms) 

40 fileobj.write('%d\n%s\n' % (natoms, comment)) 

41 for s, (x, y, z) in zip(atoms.symbols, atoms.positions): 

42 fileobj.write('%-2s %s %s %s\n' % (s, fmt % x, fmt % y, fmt % z)) 

43 

44 

45# Compatibility with older releases 

46simple_read_xyz = read_xyz 

47simple_write_xyz = write_xyz