Coverage for ase/io/turbomole.py: 49.54%

109 statements  

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

1from ase.units import Bohr 

2 

3 

4def read_turbomole(fd): 

5 """Method to read turbomole coord file 

6 

7 coords in bohr, atom types in lowercase, format: 

8 $coord 

9 x y z atomtype 

10 x y z atomtype f 

11 $end 

12 Above 'f' means a fixed atom. 

13 """ 

14 from ase import Atoms 

15 from ase.constraints import FixAtoms 

16 

17 lines = fd.readlines() 

18 atoms_pos = [] 

19 atom_symbols = [] 

20 myconstraints = [] 

21 

22 # find $coord section; 

23 # does not necessarily have to be the first $<something> in file... 

24 for i, l in enumerate(lines): 

25 if l.strip().startswith('$coord'): 

26 start = i 

27 break 

28 for line in lines[start + 1 :]: 

29 if line.startswith('$'): # start of new section 

30 break 

31 else: 

32 x, y, z, symbolraw = line.split()[:4] 

33 symbolshort = symbolraw.strip() 

34 symbol = symbolshort[0].upper() + symbolshort[1:].lower() 

35 # print(symbol) 

36 atom_symbols.append(symbol) 

37 atoms_pos.append( 

38 [float(x) * Bohr, float(y) * Bohr, float(z) * Bohr] 

39 ) 

40 cols = line.split() 

41 if len(cols) == 5: 

42 fixedstr = line.split()[4].strip() 

43 if fixedstr == 'f': 

44 myconstraints.append(True) 

45 else: 

46 myconstraints.append(False) 

47 else: 

48 myconstraints.append(False) 

49 

50 # convert Turbomole ghost atom Q to X 

51 atom_symbols = [ 

52 element if element != 'Q' else 'X' for element in atom_symbols 

53 ] 

54 atoms = Atoms(positions=atoms_pos, symbols=atom_symbols, pbc=False) 

55 c = FixAtoms(mask=myconstraints) 

56 atoms.set_constraint(c) 

57 return atoms 

58 

59 

60class TurbomoleFormatError(ValueError): 

61 default_message = ( 

62 'Data format in file does not correspond to known ' 

63 'Turbomole gradient format' 

64 ) 

65 

66 def __init__(self, *args, **kwargs): 

67 if args or kwargs: 

68 ValueError.__init__(self, *args, **kwargs) 

69 else: 

70 ValueError.__init__(self, self.default_message) 

71 

72 

73def read_turbomole_gradient(fd, index=-1): 

74 """Method to read turbomole gradient file""" 

75 

76 # read entire file 

77 lines = [x.strip() for x in fd.readlines()] 

78 

79 # find $grad section 

80 start = end = -1 

81 for i, line in enumerate(lines): 

82 if not line.startswith('$'): 

83 continue 

84 if line.split()[0] == '$grad': 

85 start = i 

86 elif start >= 0: 

87 end = i 

88 break 

89 

90 if end <= start: 

91 raise RuntimeError("File does not contain a valid '$grad' section") 

92 

93 # trim lines to $grad 

94 del lines[: start + 1] 

95 del lines[end - 1 - start :] 

96 

97 # Interpret $grad section 

98 from ase import Atom, Atoms 

99 from ase.calculators.singlepoint import SinglePointCalculator 

100 from ase.units import Bohr, Hartree 

101 

102 images = [] 

103 while lines: # loop over optimization cycles 

104 # header line 

105 # cycle = 1 SCF energy = -267.6666811409 |dE/dxyz| = 0.157112 # noqa: E501 

106 fields = lines[0].split('=') 

107 try: 

108 # cycle = int(fields[1].split()[0]) 

109 energy = float(fields[2].split()[0]) * Hartree 

110 # gradient = float(fields[3].split()[0]) 

111 except (IndexError, ValueError) as e: 

112 raise TurbomoleFormatError from e 

113 

114 # coordinates/gradient 

115 atoms = Atoms() 

116 forces = [] 

117 for line in lines[1:]: 

118 fields = line.split() 

119 if len(fields) == 4: # coordinates 

120 # 0.00000000000000 0.00000000000000 0.00000000000000 c # noqa: E501 

121 try: 

122 symbol = fields[3].lower().capitalize() 

123 # if dummy atom specified, substitute 'Q' with 'X' 

124 if symbol == 'Q': 

125 symbol = 'X' 

126 position = tuple(Bohr * float(x) for x in fields[0:3]) 

127 except ValueError as e: 

128 raise TurbomoleFormatError from e 

129 atoms.append(Atom(symbol, position)) 

130 elif len(fields) == 3: # gradients 

131 # -.51654903354681D-07 -.51654903206651D-07 0.51654903169644D-07 # noqa: E501 

132 grad = [] 

133 for val in fields[:3]: 

134 try: 

135 grad.append( 

136 -float(val.replace('D', 'E')) * Hartree / Bohr 

137 ) 

138 except ValueError as e: 

139 raise TurbomoleFormatError from e 

140 forces.append(grad) 

141 else: # next cycle 

142 break 

143 

144 # calculator 

145 calc = SinglePointCalculator(atoms, energy=energy, forces=forces) 

146 atoms.calc = calc 

147 

148 # save frame 

149 images.append(atoms) 

150 

151 # delete this frame from data to be handled 

152 del lines[: 2 * len(atoms) + 1] 

153 

154 return images[index] 

155 

156 

157def write_turbomole(fd, atoms): 

158 """Method to write turbomole coord file""" 

159 from ase.constraints import FixAtoms 

160 

161 coord = atoms.get_positions() 

162 symbols = atoms.get_chemical_symbols() 

163 

164 # convert X to Q for Turbomole ghost atoms 

165 symbols = [element if element != 'X' else 'Q' for element in symbols] 

166 

167 fix_indices = set() 

168 if atoms.constraints: 

169 for constr in atoms.constraints: 

170 if isinstance(constr, FixAtoms): 

171 fix_indices.update(constr.get_indices()) 

172 

173 fix_str = [] 

174 for i in range(len(atoms)): 

175 if i in fix_indices: 

176 fix_str.append('f') 

177 else: 

178 fix_str.append('') 

179 

180 fd.write('$coord\n') 

181 for (x, y, z), s, fix in zip(coord, symbols, fix_str): 

182 fd.write( 

183 '%20.14f %20.14f %20.14f %2s %2s \n' 

184 % (x / Bohr, y / Bohr, z / Bohr, s.lower(), fix) 

185 ) 

186 

187 fd.write('$end\n')