Coverage for ase/io/xtd.py: 69.91%

113 statements  

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

1import xml.etree.ElementTree as ET 

2from xml.dom import minidom 

3 

4import numpy as np 

5 

6from ase import Atoms 

7from ase.io.utils import connectivity2bonds 

8from ase.io.xsd import SetChild, _write_xsd_html 

9 

10_image_header = ' ' * 74 + '0.0000\n!DATE Jan 01 00:00:00 2000\n' 

11_image_footer = 'end\nend\n' 

12 

13 

14def _get_atom_str(an, xyz): 

15 s = f'{an:<5}' 

16 s += f'{xyz[0]:>15.9f}{xyz[1]:>15.9f}{xyz[2]:>15.9f}' 

17 s += ' XXXX 1 xx ' 

18 s += f'{an:<2}' 

19 s += ' 0.000\n' 

20 return s 

21 

22 

23def write_xtd(filename, images, connectivity=None, moviespeed=10): 

24 """Takes Atoms object, and write materials studio file 

25 atoms: Atoms object 

26 filename: path of the output file 

27 moviespeed: speed of animation. between 0 and 10 

28 

29 note: material studio file cannot use a partial periodic system. If partial 

30 perodic system was inputted, full periodicity was assumed. 

31 """ 

32 if moviespeed < 0 or moviespeed > 10: 

33 raise ValueError('moviespeed only between 0 and 10 allowed') 

34 

35 if hasattr(images, 'get_positions'): 

36 images = [images] 

37 

38 XSD, ATR = _write_xsd_html(images, connectivity) 

39 ATR.attrib['NumChildren'] = '2' 

40 natoms = len(images[0]) 

41 

42 if connectivity is not None: 

43 bonds = connectivity2bonds(connectivity) 

44 else: 

45 bonds = [] 

46 

47 # non-periodic system 

48 s = '!BIOSYM archive 3\n' 

49 if not images[0].pbc.all(): 

50 # Write trajectory 

51 SetChild( 

52 ATR, 

53 'Trajectory', 

54 dict( 

55 ID=str(natoms + 3 + len(bonds)), 

56 Increment='-1', 

57 End=str(len(images)), 

58 Type='arc', 

59 Speed=str(moviespeed), 

60 FrameClassType='Atom', 

61 ), 

62 ) 

63 

64 # write frame information file 

65 s += 'PBC=OFF\n' 

66 for image in images: 

67 s += _image_header 

68 s += '\n' 

69 an = image.get_chemical_symbols() 

70 xyz = image.get_positions() 

71 for i in range(natoms): 

72 s += _get_atom_str(an[i], xyz[i, :]) 

73 s += _image_footer 

74 

75 # periodic system 

76 else: 

77 SetChild( 

78 ATR, 

79 'Trajectory', 

80 dict( 

81 ID=str(natoms + 9 + len(bonds)), 

82 Increment='-1', 

83 End=str(len(images)), 

84 Type='arc', 

85 Speed=str(moviespeed), 

86 FrameClassType='Atom', 

87 ), 

88 ) 

89 

90 # write frame information file 

91 s += 'PBC=ON\n' 

92 for image in images: 

93 s += _image_header 

94 s += 'PBC' 

95 vec = image.cell.lengths() 

96 s += f'{vec[0]:>10.4f}{vec[1]:>10.4f}{vec[2]:>10.4f}' 

97 angles = image.cell.angles() 

98 s += '{:>10.4f}{:>10.4f}{:>10.4f}'.format(*angles) 

99 s += '\n' 

100 an = image.get_chemical_symbols() 

101 

102 angrad = np.deg2rad(angles) 

103 cell = np.zeros((3, 3)) 

104 cell[0, :] = [vec[0], 0, 0] 

105 cell[1, :] = ( 

106 np.array([np.cos(angrad[2]), np.sin(angrad[2]), 0]) * vec[1] 

107 ) 

108 cell[2, 0] = vec[2] * np.cos(angrad[1]) 

109 cell[2, 1] = ( 

110 vec[1] * vec[2] * np.cos(angrad[0]) - cell[1, 0] * cell[2, 0] 

111 ) / cell[1, 1] 

112 cell[2, 2] = np.sqrt( 

113 vec[2] ** 2 - cell[2, 0] ** 2 - cell[2, 1] ** 2 

114 ) 

115 xyz = np.dot(image.get_scaled_positions(), cell) 

116 for i in range(natoms): 

117 s += _get_atom_str(an[i], xyz[i, :]) 

118 s += _image_footer 

119 

120 # print arc file 

121 if isinstance(filename, str): 

122 farcname = filename[:-3] + 'arc' 

123 else: 

124 farcname = filename.name[:-3] + 'arc' 

125 

126 with open(farcname, 'w') as farc: 

127 farc.write(s) 

128 

129 # check if file is an object or not. 

130 openandclose = False 

131 try: 

132 if isinstance(filename, str): 

133 fd = open(filename, 'w') 

134 openandclose = True 

135 else: # Assume it's a 'file-like object' 

136 fd = filename 

137 

138 # Return a pretty-printed XML string for the Element. 

139 rough_string = ET.tostring(XSD, 'utf-8') 

140 reparsed = minidom.parseString(rough_string) 

141 Document = reparsed.toprettyxml(indent='\t') 

142 

143 # write 

144 fd.write(Document) 

145 finally: 

146 if openandclose: 

147 fd.close() 

148 

149 

150def read_xtd(filename, index=-1): 

151 """Import xtd file (Materials Studio) 

152 

153 Xtd files always come with arc file, and arc file 

154 contains all the relevant information to make atoms 

155 so only Arc file needs to be read 

156 """ 

157 if isinstance(filename, str): 

158 arcfilename = filename[:-3] + 'arc' 

159 else: 

160 arcfilename = filename.name[:-3] + 'arc' 

161 

162 # This trick with opening a totally different file is a gross violation of 

163 # common sense. 

164 with open(arcfilename) as fd: 

165 return read_arcfile(fd, index) 

166 

167 

168def read_arcfile(fd, index): 

169 images = [] 

170 

171 # the first line is comment 

172 fd.readline() 

173 pbc = 'ON' in fd.readline() 

174 L = fd.readline() 

175 while L != '': 

176 if '!' not in L: # flag for the start of an image 

177 L = fd.readline() 

178 continue 

179 if pbc: 

180 L = fd.readline() 

181 cell = [float(d) for d in L.split()[1:]] 

182 else: 

183 fd.readline() 

184 symbols = [] 

185 coords = [] 

186 while True: 

187 line = fd.readline() 

188 L = line.split() 

189 if not line or 'end' in L: 

190 break 

191 symbols.append(L[0]) 

192 coords.append([float(x) for x in L[1:4]]) 

193 if pbc: 

194 image = Atoms(symbols, positions=coords, cell=cell, pbc=pbc) 

195 else: 

196 image = Atoms(symbols, positions=coords, pbc=pbc) 

197 images.append(image) 

198 L = fd.readline() 

199 

200 if not index: 

201 return images 

202 else: 

203 return images[index]