Coverage for ase/utils/sphinx_create_png.py: 11.56%

173 statements  

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

1import os 

2import re 

3import runpy 

4import traceback 

5import warnings 

6from os.path import join 

7from pathlib import Path 

8from stat import ST_MTIME 

9from subprocess import DEVNULL, CalledProcessError, check_call 

10 

11from docutils import nodes 

12from docutils.parsers.rst.roles import set_classes 

13 

14 

15def png_scraper(block, block_vars, gallery_conf): 

16 import shutil 

17 

18 from sphinx_gallery.scrapers import figure_rst 

19 

20 src_file = Path(block_vars['src_file']) 

21 src_dir = src_file.parent 

22 

23 pngs = sorted(src_dir.glob('*.png')) 

24 

25 image_names = [] 

26 image_path_iterator = block_vars['image_path_iterator'] 

27 

28 for png in pngs: 

29 this_image_path = image_path_iterator.next() 

30 image_names.append(this_image_path) 

31 shutil.move(png, this_image_path) 

32 

33 return figure_rst(image_names, gallery_conf['src_dir']) 

34 

35 

36def mol_role(role, rawtext, text, lineno, inliner, options=None, content=None): 

37 if content is None: 

38 content = [] 

39 if options is None: 

40 options = {} 

41 n = [] 

42 t = '' 

43 while text: 

44 if text[0] == '_': 

45 n.append(nodes.inline(text=t)) 

46 t = '' 

47 m = re.match(r'\d+', text[1:]) 

48 if m is None: 

49 raise RuntimeError('Expected one or more digits after "_"') 

50 digits = m.group() 

51 n.append(nodes.subscript(text=digits)) 

52 text = text[1 + len(digits) :] 

53 else: 

54 t += text[0] 

55 text = text[1:] 

56 n.append(nodes.inline(text=t)) 

57 return n, [] 

58 

59 

60def git_role_tmpl( 

61 urlroot, role, rawtext, text, lineno, inliner, options=None, content=None 

62): 

63 if content is None: 

64 content = [] 

65 if options is None: 

66 options = {} 

67 env = inliner.document.settings.env 

68 srcdir = Path(env.srcdir) 

69 project_root = srcdir.parent 

70 # The asserts below are commented out because this role template 

71 # is also used by other projects, such as GPAW and Asap. 

72 # assert srcdir.name == 'doc' 

73 # assert project_root.name == 'ase' 

74 

75 if text[-1] == '>': 

76 i = text.index('<') 

77 name = text[: i - 1] 

78 text = text[i + 1 : -1] 

79 else: 

80 name = text 

81 if name[0] == '~': 

82 name = name.split('/')[-1] 

83 text = text[1:] 

84 if '?' in name: 

85 name = name[: name.index('?')] 

86 

87 # Check if the link is broken 

88 is_tag = text.startswith('..') # Tags are like :git:`3.19.1 <../3.19.1>` 

89 path = project_root / text 

90 

91 if not (is_tag or path.exists()): 

92 msg = f'Broken link: {rawtext}: Non-existing path: {path}' 

93 msg = inliner.reporter.error(msg, line=lineno) 

94 prb = inliner.problematic(rawtext, rawtext, msg) 

95 return [prb], [msg] 

96 ref = urlroot + text 

97 set_classes(options) 

98 node = nodes.reference(rawtext, name, refuri=ref, **options) 

99 return [node], [] 

100 

101 

102def git_role(role, rawtext, text, lineno, inliner, options=None, content=None): 

103 if content is None: 

104 content = [] 

105 if options is None: 

106 options = {} 

107 return git_role_tmpl( 

108 'https://gitlab.com/ase/ase/blob/master/', 

109 role, 

110 rawtext, 

111 text, 

112 lineno, 

113 inliner, 

114 options, 

115 content, 

116 ) 

117 

118 

119def setup(app): 

120 app.add_role('mol', mol_role) 

121 app.add_role('git', git_role) 

122 create_png_files() 

123 

124 

125def creates(): 

126 """Generator for Python scripts and their output filenames.""" 

127 for dirpath, dirnames, filenames in sorted(os.walk('.')): 

128 if dirpath.startswith('./build'): 

129 # Skip files in the build/ folder 

130 continue 

131 

132 for filename in sorted(filenames): 

133 if filename.endswith('.py'): 

134 path = join(dirpath, filename) 

135 with open(path) as fd: 

136 lines = fd.readlines() 

137 if len(lines) == 0: 

138 continue 

139 if 'coding: utf-8' in lines[0]: 

140 lines.pop(0) 

141 outnames = [] 

142 for line in lines: 

143 if line.startswith('# creates:'): 

144 outnames.extend( 

145 [file.rstrip(',') for file in line.split()[2:]] 

146 ) 

147 else: 

148 break 

149 if outnames: 

150 yield dirpath, filename, outnames 

151 

152 

153def create_png_files(raise_exceptions=False): 

154 from ase.utils import workdir 

155 

156 try: 

157 check_call(['povray', '-h'], stderr=DEVNULL) 

158 except (FileNotFoundError, CalledProcessError): 

159 warnings.warn('No POVRAY!') 

160 # Replace write_pov with write_png: 

161 from ase.io import pov 

162 from ase.io.png import write_png 

163 

164 def write_pov( 

165 filename, 

166 atoms, 

167 povray_settings=None, 

168 isosurface_data=None, 

169 **generic_projection_settings, 

170 ): 

171 if povray_settings is None: 

172 povray_settings = {} 

173 write_png( 

174 Path(filename).with_suffix('.png'), 

175 atoms, 

176 **generic_projection_settings, 

177 ) 

178 

179 class DummyRenderer: 

180 def render(self): 

181 pass 

182 

183 return DummyRenderer() 

184 

185 pov.write_pov = write_pov 

186 

187 for dir, pyname, outnames in creates(): 

188 path = join(dir, pyname) 

189 t0 = os.stat(path)[ST_MTIME] 

190 run = False 

191 for outname in outnames: 

192 try: 

193 t = os.stat(join(dir, outname))[ST_MTIME] 

194 except OSError: 

195 run = True 

196 break 

197 else: 

198 if t < t0: 

199 run = True 

200 break 

201 if run: 

202 print('running:', path) 

203 with workdir(dir): 

204 import matplotlib.pyplot as plt 

205 

206 plt.figure() 

207 try: 

208 runpy.run_path(pyname, run_name='__main__') 

209 except KeyboardInterrupt: 

210 return 

211 except Exception: 

212 if raise_exceptions: 

213 raise 

214 else: 

215 traceback.print_exc() 

216 

217 for n in plt.get_fignums(): 

218 plt.close(n) 

219 

220 for outname in outnames: 

221 print(dir, outname) 

222 

223 

224def clean(): 

225 """Remove all generated files.""" 

226 for dir, pyname, outnames in creates(): 

227 for outname in outnames: 

228 if os.path.isfile(os.path.join(dir, outname)): 

229 os.remove(os.path.join(dir, outname)) 

230 

231 

232def visual_inspection(): 

233 """Manually inspect generated files.""" 

234 import subprocess 

235 

236 images = [] 

237 text = [] 

238 pdf = [] 

239 for dir, pyname, outnames in creates(): 

240 for outname in outnames: 

241 path = os.path.join(dir, outname) 

242 ext = path.rsplit('.', 1)[1] 

243 if ext == 'pdf': 

244 pdf.append(path) 

245 elif ext in ['csv', 'txt', 'out', 'css', 'LDA', 'rst']: 

246 text.append(path) 

247 else: 

248 images.append(path) 

249 subprocess.call(['eog'] + images) 

250 subprocess.call(['evince'] + pdf) 

251 subprocess.call(['more'] + text) 

252 

253 

254if __name__ == '__main__': 

255 import argparse 

256 

257 parser = argparse.ArgumentParser(description='Process generated files.') 

258 parser.add_argument( 

259 'command', 

260 nargs='?', 

261 default='list', 

262 choices=['list', 'inspect', 'clean', 'run'], 

263 ) 

264 args = parser.parse_args() 

265 if args.command == 'clean': 

266 clean() 

267 elif args.command == 'list': 

268 for dir, pyname, outnames in creates(): 

269 for outname in outnames: 

270 print(os.path.join(dir, outname)) 

271 elif args.command == 'run': 

272 create_png_files(raise_exceptions=True) 

273 else: 

274 visual_inspection()