Coverage for ase/io/gen.py: 93.33%

90 statements  

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

1"""Extension to ASE: read and write structures in GEN format 

2 

3Refer to DFTB+ manual for GEN format description. 

4 

5Note: GEN format only supports single snapshot. 

6""" 

7 

8import re 

9from collections.abc import Sequence 

10 

11from ase.atoms import Atoms 

12from ase.utils import reader, writer 

13 

14 

15@reader 

16def read_gen(fileobj): 

17 """Read structure in GEN format (refer to DFTB+ manual). 

18 Multiple snapshot are not allowed.""" 

19 image = Atoms() 

20 lines = fileobj.readlines() 

21 line = lines[0].split() 

22 natoms = int(line[0]) 

23 pb_flag = line[1] 

24 if line[1] not in ['C', 'F', 'S']: 

25 if line[1] == 'H': 

26 raise OSError( 

27 'Error in line #1: H (Helical) is valid but not ' 

28 'supported. Only C (Cluster), S (Supercell) ' 

29 'or F (Fraction) are supported options' 

30 ) 

31 else: 

32 raise OSError( 

33 'Error in line #1: only C (Cluster), S (Supercell) ' 

34 'or F (Fraction) are supported options' 

35 ) 

36 

37 # Read atomic symbols 

38 line = lines[1].split() 

39 symboldict = {symbolid: symb for symbolid, symb in enumerate(line, start=1)} 

40 # Read atoms (GEN format supports only single snapshot) 

41 del lines[:2] 

42 positions = [] 

43 symbols = [] 

44 tags = [] 

45 for line in lines[:natoms]: 

46 _dummy, symbolid, x, y, z = line.split()[:5] 

47 symbol = symboldict[int(symbolid)] 

48 parts = re.findall(r'\d+|[a-zA-Z]+', symbol) 

49 if len(parts) == 1: 

50 symbols.append(parts[0]) 

51 else: 

52 # If symbolid contains digits, it is a tag 

53 symbols.append(parts[0]) 

54 tags.append(int(parts[1])) 

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

56 if not tags: 

57 tags = None 

58 image = Atoms(symbols=symbols, positions=positions, tags=tags) 

59 del lines[:natoms] 

60 

61 # If Supercell, parse periodic vectors. 

62 # If Fraction, translate into Supercell. 

63 if pb_flag == 'C': 

64 return image 

65 else: 

66 # Dummy line: line after atom positions is not uniquely defined 

67 # in gen implementations, and not necessary in DFTB package 

68 del lines[:1] 

69 image.set_pbc([True, True, True]) 

70 p = [] 

71 for i in range(3): 

72 x, y, z = lines[i].split()[:3] 

73 p.append([float(x), float(y), float(z)]) 

74 image.set_cell( 

75 [ 

76 (p[0][0], p[0][1], p[0][2]), 

77 (p[1][0], p[1][1], p[1][2]), 

78 (p[2][0], p[2][1], p[2][2]), 

79 ] 

80 ) 

81 if pb_flag == 'F': 

82 frac_positions = image.get_positions() 

83 image.set_scaled_positions(frac_positions) 

84 return image 

85 

86 

87@writer 

88def write_gen( 

89 fileobj, 

90 images: Atoms | Sequence[Atoms], 

91 fractional: bool = False, 

92 with_tags=False, 

93): 

94 """Write structure in GEN format (refer to DFTB+ manual). 

95 Multiple snapshots are not allowed.""" 

96 if isinstance(images, (list, tuple)): 

97 # GEN format doesn't support multiple snapshots 

98 if len(images) != 1: 

99 raise ValueError( 

100 '"images" contains more than one structure. ' 

101 'GEN format supports only single snapshot output.' 

102 ) 

103 atoms = images[0] 

104 else: 

105 atoms = images 

106 

107 symbols = atoms.get_chemical_symbols() 

108 tags = atoms.get_tags() 

109 

110 # Define a dictionary with symbols-id 

111 symboldict: dict[str, int] = {} 

112 for sym, tag in zip(symbols, tags): 

113 sym = f'{sym}{tag}' if with_tags else sym 

114 if sym not in symboldict: 

115 symboldict[sym] = len(symboldict) + 1 

116 # An ordered symbol list is needed as ordered dictionary 

117 # is just available in python 2.7 

118 orderedsymbols = list(['null'] * len(symboldict.keys())) 

119 for sym, num in symboldict.items(): 

120 orderedsymbols[num - 1] = sym 

121 

122 # Check whether the structure is periodic 

123 # GEN cannot describe periodicity in one or two direction, 

124 # a periodic structure is considered periodic in all the 

125 # directions. If your structure is not periodical in all 

126 # the directions, be sure you have set big periodicity 

127 # vectors in the non-periodic directions 

128 if fractional: 

129 pb_flag = 'F' 

130 elif atoms.pbc.any(): 

131 pb_flag = 'S' 

132 else: 

133 pb_flag = 'C' 

134 

135 natoms = len(symbols) 

136 ind = 0 

137 

138 fileobj.write(f'{natoms:d} {pb_flag:<5s}\n') 

139 for sym in orderedsymbols: 

140 fileobj.write(f'{sym:<7s}') 

141 fileobj.write('\n') 

142 

143 if fractional: 

144 coords = atoms.get_scaled_positions(wrap=False) 

145 else: 

146 coords = atoms.get_positions(wrap=False) 

147 

148 for sym, tag, (x, y, z) in zip(symbols, tags, coords): 

149 ind += 1 

150 sym = f'{sym}{tag}' if with_tags else sym 

151 symbolid = symboldict[sym] 

152 fileobj.write( 

153 f'{ind:-6d} {symbolid:d} {x:22.15f} {y:22.15f} {z:22.15f}\n' 

154 ) 

155 

156 if atoms.pbc.any() or fractional: 

157 fileobj.write(f'{0.0:22.15f} {0.0:22.15f} {0.0:22.15f} \n') 

158 cell = atoms.get_cell() 

159 for i in range(3): 

160 for j in range(3): 

161 fileobj.write(f'{cell[i, j]:22.15f} ') 

162 fileobj.write('\n')