Coverage for ase/_4/plugins/io.py: 74.51%

102 statements  

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

1import importlib 

2import re 

3from collections.abc import Callable, Iterator, Sequence 

4from functools import cached_property 

5from importlib.metadata import EntryPoint 

6from types import ModuleType 

7from typing import ( 

8 Any, 

9 BinaryIO, 

10 Concatenate, 

11 Literal, 

12 Self, 

13 TextIO, 

14) 

15 

16from ase.atoms import Atoms 

17from ase.io.formats import IOFormat 

18 

19from .plugin import MissingFunction, Plugin 

20 

21 

22class IOFormatPlugin(Plugin): 

23 def __init__( 

24 self, 

25 name: str, 

26 *, 

27 citation: str, 

28 module: ModuleType | None = None, 

29 description: str, 

30 code: str, 

31 reader: str 

32 | Callable[[], Callable[..., Atoms | Iterator[Atoms]]] 

33 | None, 

34 writer: str 

35 | Callable[ 

36 [], Callable[Concatenate[str | BinaryIO | TextIO, Atoms, ...], None] 

37 ] 

38 | None, 

39 encoding: str | None = None, 

40 extensions: list[str] | None = None, 

41 globs: list[str] | None = None, 

42 magic: list[str] | None = None, 

43 magic_regex: bytes | None | None = None, 

44 ): 

45 super().__init__(name=name, citation=citation, module=module) 

46 

47 if not any((reader, writer)): 

48 raise ValueError('IOFormatPlugin must provide a reader or a writer') 

49 

50 self.name = name 

51 self.description = description 

52 

53 assert len(code) == 2 

54 assert code[0] in list('+1') 

55 assert code[1] in list('BFS') 

56 self.code = code 

57 self.encoding = encoding 

58 

59 self._reader = reader 

60 self._writer = writer 

61 

62 self.extensions = extensions if extensions else [] 

63 self.globs = globs if globs else [] 

64 self.magic = magic if magic else [] 

65 self.magic_regex = magic_regex 

66 

67 @cached_property 

68 def can_read(self) -> bool: 

69 """Check if plugin implements a reader 

70 

71 If this is false, read() will raise an error 

72 """ 

73 return self._reader is not None 

74 

75 @cached_property 

76 def can_write(self) -> bool: 

77 """Check if plugin implements a writer 

78 

79 If this is false, write() will raise an error 

80 """ 

81 return self._writer is not None 

82 

83 def read( 

84 self, *args: list[Any], **kwargs: dict[str, Any] 

85 ) -> Atoms | Iterator[Atoms]: 

86 if not self.can_read: 

87 raise ValueError('This plugin does not implement a reader') 

88 assert self._resolved_reader is not None 

89 return self._resolved_reader(*args, **kwargs) 

90 

91 def write( 

92 self, 

93 filename: str | BinaryIO | TextIO, 

94 images: Atoms | Sequence[Atoms], 

95 *args: list[Any], 

96 **kwargs: dict[str, Any], 

97 ) -> None: 

98 if not self.can_write: 

99 raise ValueError('This plugin does not implement a writer') 

100 assert self._resolved_writer is not None 

101 self._resolved_writer(filename, images, *args, **kwargs) 

102 

103 @cached_property 

104 def _resolved_reader(self) -> Callable[..., Atoms | Iterator[Atoms]] | None: 

105 if self._reader is None: 

106 return None 

107 return self._resolve(self._reader) # type: ignore[no-any-return] 

108 

109 @cached_property 

110 def _resolved_writer( 

111 self, 

112 ) -> ( 

113 Callable[ 

114 Concatenate[str | BinaryIO | TextIO, Atoms | Sequence[Atoms], ...], 

115 None, 

116 ] 

117 | None 

118 ): 

119 if self._writer is None: 

120 return None 

121 return self._resolve(self._writer) # type: ignore[no-any-return] 

122 

123 def match_name(self, basename: str) -> bool: 

124 from fnmatch import fnmatch 

125 

126 return any(fnmatch(basename, pattern) for pattern in self.globs) 

127 

128 def match_magic(self, data: bytes) -> bool: 

129 if self.magic_regex: 

130 assert not self.magic, 'Define only one of magic and magic_regex' 

131 match = re.match(self.magic_regex, data, re.M | re.S) 

132 return match is not None 

133 

134 from fnmatch import fnmatchcase 

135 

136 return any( 

137 fnmatchcase(data, magic + b'*') # type: ignore[operator, type-var] 

138 for magic in self.magic 

139 ) 

140 

141 

142class LegacyIOFormatPlugin(IOFormatPlugin): 

143 """Wrapper for old IOFormat class to new plugin system 

144 

145 Note that __init__ is the same as IOFormatPlugin: this class 

146 should typically be constructed using the 

147 .from_legacy_ioformat or .from_legacy_entry_point classmethod. 

148 """ 

149 

150 @cached_property 

151 def can_read(self) -> bool: 

152 """Check if plugin implements a reader 

153 

154 If this is false, read() will raise an error 

155 

156 New IOFormatPlugin stores a missing reader as None, but for legacy 

157 implementations we have to check the module content at this point. 

158 """ 

159 try: 

160 self._resolved_reader 

161 except MissingFunction: 

162 return False 

163 return True 

164 

165 @cached_property 

166 def can_write(self) -> bool: 

167 """Check if plugin implements a writer 

168 

169 If this is false, write() will raise an error 

170 """ 

171 try: 

172 self._resolved_writer 

173 except MissingFunction: 

174 return False 

175 return True 

176 

177 @staticmethod 

178 def _legacy_function_loader( 

179 name: str, 

180 module_name: str, 

181 prefix: Literal['read_', 'write_'], 

182 error_message: str, 

183 ) -> Callable[[], Callable[..., Any]]: 

184 """Get specially-named function from a module, wrapped in Callable 

185 

186 This is a compatibility tool for working with the legacy IOFormat 

187 

188 """ 

189 

190 def func() -> Callable[..., Any]: 

191 formatname = name.replace('-', '_') 

192 module = importlib.import_module(module_name) 

193 legacy_function = getattr(module, prefix + formatname, None) 

194 if legacy_function is None: 

195 raise MissingFunction(error_message) 

196 return legacy_function # type: ignore[no-any-return] 

197 

198 return func 

199 

200 @classmethod 

201 def from_legacy_io_format( 

202 cls, 

203 io_format: IOFormat, 

204 module: ModuleType | None, 

205 citation: str = '', 

206 ) -> Self: 

207 

208 reader = cls._legacy_function_loader( 

209 io_format.name, 

210 io_format.module_name, 

211 'read_', 

212 f"Can't read from {io_format.name}-format", 

213 ) 

214 writer = cls._legacy_function_loader( 

215 io_format.name, 

216 io_format.module_name, 

217 'write_', 

218 f"Can't write to {io_format.name}-format", 

219 ) 

220 

221 plugin = cls( 

222 name=io_format.name, 

223 module=module, 

224 citation='Imported from legacy IOFormat', 

225 description=io_format.description, 

226 code=io_format.code, 

227 encoding=io_format.encoding, 

228 reader=reader, 

229 writer=writer, 

230 extensions=io_format.extensions, 

231 globs=io_format.globs, 

232 magic=io_format.magic, 

233 magic_regex=io_format.magic_regex, 

234 ) 

235 return plugin 

236 

237 @classmethod 

238 def from_legacy_entry_point( 

239 cls, 

240 entry_point: EntryPoint, 

241 ) -> Self: 

242 fmt = entry_point.load() 

243 

244 reader = cls._legacy_function_loader( 

245 entry_point.name, 

246 entry_point.module, 

247 'read_', 

248 f"Can't read from {entry_point.name}-format", 

249 ) 

250 

251 writer = cls._legacy_function_loader( 

252 entry_point.name, 

253 entry_point.module, 

254 'write_', 

255 f"Can't write to {entry_point.name}-format", 

256 ) 

257 

258 # Note that the "module" attribute of a Plugin should represent where 

259 # the *plugin* comes from, rather than its underlying implementation 

260 # 

261 # Wrapped legacy plugins are a slight grey area but is seems much more 

262 # informative to use the external package 

263 plugin = cls( 

264 name=entry_point.name, 

265 module=importlib.import_module(entry_point.module), 

266 citation='Imported from legacy ExternalIOFormat', 

267 description=fmt.desc, 

268 code=fmt.code, 

269 reader=reader, 

270 writer=writer, 

271 extensions=fmt.ext, 

272 globs=fmt.glob, 

273 magic=fmt.magic, 

274 magic_regex=fmt.magic_regex, 

275 ) 

276 return plugin