Coverage for ase/io/gromacs.py: 90.18%

112 statements  

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

1""" 

2read and write gromacs geometry files 

3""" 

4 

5import numpy as np 

6 

7from ase import units 

8from ase.atoms import Atoms 

9from ase.data import atomic_numbers 

10from ase.utils import reader, writer 

11 

12 

13@reader 

14def read_gromacs(fd): 

15 """From: 

16 http://manual.gromacs.org/current/online/gro.html 

17 C format 

18 "%5d%-5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f" 

19 python: starting from 0, including first excluding last 

20 0:4 5:10 10:15 15:20 20:28 28:36 36:44 44:52 52:60 60:68 

21 

22 Import gromacs geometry type files (.gro). 

23 Reads atom positions, 

24 velocities(if present) and 

25 simulation cell (if present) 

26 """ 

27 

28 atoms = Atoms() 

29 lines = fd.readlines() 

30 positions = [] 

31 gromacs_velocities = [] 

32 symbols = [] 

33 tags = [] 

34 gromacs_residuenumbers = [] 

35 gromacs_residuenames = [] 

36 gromacs_atomtypes = [] 

37 sym2tag = {} 

38 tag = 0 

39 for line in lines[2:-1]: 

40 # print(line[0:5]+':'+line[5:10]+':'+line[10:15]+':'+line[15:20]) 

41 # it is not a good idea to use the split method with gromacs input 

42 # since the fields are defined by a fixed column number. Therefore, 

43 # they may not be space between the fields 

44 # inp = line.split() 

45 

46 floatvect = ( 

47 float(line[20:28]) * 10.0, 

48 float(line[28:36]) * 10.0, 

49 float(line[36:44]) * 10.0, 

50 ) 

51 positions.append(floatvect) 

52 

53 # read velocities 

54 velocities = np.array([0.0, 0.0, 0.0]) 

55 vx = line[44:52].strip() 

56 vy = line[52:60].strip() 

57 vz = line[60:68].strip() 

58 

59 for iv, vxyz in enumerate([vx, vy, vz]): 

60 if len(vxyz) > 0: 

61 try: 

62 velocities[iv] = float(vxyz) 

63 except ValueError as exc: 

64 raise ValueError( 

65 'can not convert velocity to float' 

66 ) from exc 

67 else: 

68 velocities = None 

69 

70 if velocities is not None: 

71 # velocities from nm/ps to ase units 

72 velocities *= units.nm / (1000.0 * units.fs) 

73 gromacs_velocities.append(velocities) 

74 

75 gromacs_residuenumbers.append(int(line[0:5])) 

76 gromacs_residuenames.append(line[5:10].strip()) 

77 

78 symbol_read = line[10:15].strip()[0:2] 

79 if symbol_read not in sym2tag: 

80 sym2tag[symbol_read] = tag 

81 tag += 1 

82 

83 tags.append(sym2tag[symbol_read]) 

84 if symbol_read in atomic_numbers: 

85 symbols.append(symbol_read) 

86 elif symbol_read[0] in atomic_numbers: 

87 symbols.append(symbol_read[0]) 

88 elif symbol_read[-1] in atomic_numbers: 

89 symbols.append(symbol_read[-1]) 

90 else: 

91 # not an atomic symbol 

92 # if we can not determine the symbol, we use 

93 # the dummy symbol X 

94 symbols.append('X') 

95 

96 gromacs_atomtypes.append(line[10:15].strip()) 

97 

98 line = lines[-1] 

99 atoms = Atoms(symbols, positions, tags=tags) 

100 

101 if len(gromacs_velocities) == len(atoms): 

102 atoms.set_velocities(gromacs_velocities) 

103 elif len(gromacs_velocities) != 0: 

104 raise ValueError('Some atoms velocities were not specified!') 

105 

106 if not atoms.has('residuenumbers'): 

107 atoms.new_array('residuenumbers', gromacs_residuenumbers, int) 

108 atoms.set_array('residuenumbers', gromacs_residuenumbers, int) 

109 if not atoms.has('residuenames'): 

110 atoms.new_array('residuenames', gromacs_residuenames, str) 

111 atoms.set_array('residuenames', gromacs_residuenames, str) 

112 if not atoms.has('atomtypes'): 

113 atoms.new_array('atomtypes', gromacs_atomtypes, str) 

114 atoms.set_array('atomtypes', gromacs_atomtypes, str) 

115 

116 # determine PBC and unit cell 

117 atoms.pbc = False 

118 inp = lines[-1].split() 

119 try: 

120 grocell = list(map(float, inp)) 

121 except ValueError: 

122 return atoms 

123 

124 if len(grocell) < 3: 

125 return atoms 

126 

127 cell = np.diag(grocell[:3]) 

128 

129 if len(grocell) >= 9: 

130 cell.flat[[1, 2, 3, 5, 6, 7]] = grocell[3:9] 

131 

132 atoms.cell = cell * 10.0 

133 atoms.pbc = True 

134 return atoms 

135 

136 

137@writer 

138def write_gromacs(fileobj, atoms): 

139 """Write gromacs geometry files (.gro). 

140 

141 Writes: 

142 

143 * atom positions, 

144 * velocities (if present, otherwise 0) 

145 * simulation cell (if present) 

146 """ 

147 

148 natoms = len(atoms) 

149 try: 

150 gromacs_residuenames = atoms.get_array('residuenames') 

151 except KeyError: 

152 gromacs_residuenames = [] 

153 for _ in range(natoms): 

154 gromacs_residuenames.append('1DUM') 

155 try: 

156 gromacs_atomtypes = atoms.get_array('atomtypes') 

157 except KeyError: 

158 gromacs_atomtypes = atoms.get_chemical_symbols() 

159 

160 try: 

161 residuenumbers = atoms.get_array('residuenumbers') 

162 except KeyError: 

163 residuenumbers = np.ones(natoms, int) 

164 

165 pos = atoms.get_positions() 

166 pos = pos / 10.0 

167 

168 vel = atoms.get_velocities() 

169 if vel is None: 

170 vel = pos * 0.0 

171 else: 

172 vel *= 1000.0 * units.fs / units.nm 

173 

174 # No "#" in the first line to prevent read error in VMD 

175 fileobj.write('A Gromacs structure file written by ASE \n') 

176 fileobj.write('%5d\n' % len(atoms)) 

177 # gromacs line see 

178 # manual.gromacs.org/documentation/current/user-guide/file-formats.html#gro 

179 # (EDH: link seems broken as of 2020-02-21) 

180 # 1WATER OW1 1 0.126 1.624 1.679 0.1227 -0.0580 0.0434 

181 for count, (resnb, resname, atomtype, xyz, vxyz) in enumerate( 

182 zip(residuenumbers, gromacs_residuenames, gromacs_atomtypes, pos, vel), 

183 start=1, 

184 ): 

185 # THIS SHOULD BE THE CORRECT, PYTHON FORMATTING, EQUIVALENT TO THE 

186 # C FORMATTING GIVEN IN THE GROMACS DOCUMENTATION: 

187 # >>> %5d%-5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f <<< 

188 line = ( 

189 '{:>5d}{:<5s}{:>5s}{:>5d}{:>8.3f}{:>8.3f}{:>8.3f}' 

190 '{:>8.4f}{:>8.4f}{:>8.4f}\n'.format( 

191 resnb, 

192 resname, 

193 atomtype, 

194 count, 

195 xyz[0], 

196 xyz[1], 

197 xyz[2], 

198 vxyz[0], 

199 vxyz[1], 

200 vxyz[2], 

201 ) 

202 ) 

203 

204 fileobj.write(line) 

205 # write box geometry 

206 if atoms.get_pbc().any(): 

207 # gromacs manual (manual.gromacs.org/online/gro.html) says: 

208 # v1(x) v2(y) v3(z) v1(y) v1(z) v2(x) v2(z) v3(x) v3(y) 

209 # 

210 # cell[i,j] is the jth Cartesian coordinate of the ith unit vector 

211 # cell[0,0] cell[1,1] cell[2,2] v1(x) v2(y) v3(z) fv0[0 1 2] 

212 # cell[0,1] cell[0,2] cell[1,0] v1(y) v1(z) v2(x) fv1[0 1 2] 

213 # cell[1,2] cell[2,0] cell[2,1] v2(z) v3(x) v3(y) fv2[0 1 2] 

214 grocell = atoms.cell.flat[[0, 4, 8, 1, 2, 3, 5, 6, 7]] * 0.1 

215 fileobj.write(''.join(['{:10.5f}'.format(x) for x in grocell])) 

216 fileobj.write('\n') 

217 else: 

218 # When we do not have a cell, the cell is specified as an empty line 

219 fileobj.write('\n')