Coverage for ase/_4/plugins/plugin_collection.py: 95.12%

82 statements  

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

1from __future__ import annotations 

2 

3from collections import defaultdict 

4from collections.abc import Callable, Collection, Iterator 

5from functools import cached_property 

6from importlib.metadata import entry_points 

7from types import ModuleType 

8from typing import Any, Self, TypeVar, cast 

9 

10from .io import IOFormatPlugin 

11from .plugin import CalculatorPlugin, Plugin 

12from .viewer import ViewerPlugin 

13 

14P = TypeVar('P', bound=Plugin, covariant=True) 

15_P = TypeVar('_P', bound=Plugin) 

16 

17 

18class PluginCollection(Collection[P]): 

19 """Collection of ASE plugins 

20 

21 The quasi-global set of installed ASE plugins will be available as an 

22 instance of Plugins at ase.plugins.plugins 

23 

24 Other instances of Plugins might be created as a useful subset (e.g. just 

25 instances of CalculatorPlugin) or for testing purposes. 

26 

27 Plugins.plugin_set is a frozenset of Plugin; it cannot be mutated but can 

28 be replaced if you have a really good reason to do so. 

29 """ 

30 

31 _cached_properties = 'by_package', 'by_type' 

32 

33 def __init__(self, plugins: Collection[P]) -> None: 

34 self.plugins = frozenset(plugins) 

35 

36 def __setattr__(self, name: str, value: Any) -> None: 

37 super().__setattr__(name, value) 

38 

39 """Invalidate cached properties""" 

40 if name == 'plugins': 

41 for attr in self._cached_properties: 

42 self.__dict__.pop(attr, None) 

43 

44 def __contains__(self, other: object) -> bool: 

45 return other in self.plugins 

46 

47 def __iter__(self) -> Iterator[P]: 

48 return iter(self.plugins) 

49 

50 def __len__(self) -> int: 

51 return len(self.plugins) 

52 

53 def __hash__(self) -> int: 

54 return hash((type(self), self.plugins)) 

55 

56 def __eq__(self, other: Any) -> bool: 

57 return (type(other) is type(self)) and other.plugins == self.plugins 

58 

59 def __repr__(self) -> str: 

60 return f'{self.__class__.__name__}({repr(self.plugins)})' 

61 

62 @staticmethod 

63 def _modulesetter(module: ModuleType) -> Callable[[_P], _P]: 

64 def set_module(plugin: _P) -> _P: 

65 if plugin.module is None: 

66 plugin.module = module 

67 return plugin 

68 

69 return set_module 

70 

71 @classmethod 

72 def from_entry_points(cls, group: str = 'ase.plugins') -> Self: 

73 """Instantiate collection from Plugins registered as entry points 

74 

75 Note that if __ase_plugins__ is missing from a registered entry point, 

76 it will be skipped quietly. 

77 """ 

78 group_entry_points = entry_points(group=group) 

79 

80 modules = (e_p.load() for e_p in group_entry_points) 

81 plugin_set: set[P] = set() 

82 

83 for module in modules: 

84 plugins: Collection[P] = getattr(module, '__ase_plugins__', set()) 

85 plugin_set = plugin_set | set( 

86 map(cls._modulesetter(module), plugins) 

87 ) 

88 

89 return cls(plugin_set) 

90 

91 @cached_property 

92 def by_package(self) -> defaultdict[str, PluginCollection[Plugin]]: 

93 plugins_by_package = defaultdict(set) 

94 for plugin in self: 

95 plugins_by_package[plugin.package].add(plugin) 

96 

97 plugincollections_by_package: defaultdict[ 

98 str, PluginCollection[Plugin] 

99 ] = defaultdict(lambda: type(self)(set())) 

100 plugincollections_by_package.update( 

101 { 

102 key: type(self)(value) 

103 for key, value in plugins_by_package.items() 

104 } 

105 ) 

106 return plugincollections_by_package 

107 

108 @cached_property 

109 def by_type(self) -> dict[type[Plugin], PluginCollection[Plugin]]: 

110 """Get a dict of PluginCollections grouped by Plugin type 

111 

112 The CalculatorPlugin and IOFormatPlugin groups are treated specially, 

113 and will include plugins that are subclasses. Any remaining plugin 

114 types will be listed separately. 

115 """ 

116 plugins_by_type: defaultdict[type[Plugin], set[Plugin]] = defaultdict( 

117 set 

118 ) 

119 

120 for plugin in self.plugins: 

121 if isinstance(plugin, CalculatorPlugin): 

122 plugins_by_type[CalculatorPlugin].add(plugin) 

123 elif isinstance(plugin, IOFormatPlugin): 

124 plugins_by_type[IOFormatPlugin].add(plugin) 

125 else: 

126 plugins_by_type[type(plugin)].add(plugin) 

127 

128 plugincollections_by_type: dict[ 

129 type[Plugin], PluginCollection[Plugin] 

130 ] = { 

131 # From Python 3.13 should be able to use type(self)[Plugin] 

132 # (So far mypy doesn't like it...) 

133 key: PluginCollection(plugin_set) 

134 for key, plugin_set in plugins_by_type.items() 

135 } 

136 

137 # CalculatorPlugin and IOFormatPlugin groups should always be present 

138 # but may be empty collections. 

139 plugincollections_by_type.setdefault( 

140 CalculatorPlugin, type(self)(set()) 

141 ) 

142 plugincollections_by_type.setdefault(IOFormatPlugin, type(self)(set())) 

143 

144 return plugincollections_by_type 

145 

146 @property 

147 def calculators(self) -> PluginCollection[CalculatorPlugin]: 

148 """Get a PluginCollection containing only CalculatorPlugins""" 

149 return cast( 

150 PluginCollection[CalculatorPlugin], self.by_type[CalculatorPlugin] 

151 ) 

152 

153 @property 

154 def io_formats(self) -> PluginCollection[IOFormatPlugin]: 

155 """Get a PluginCollection containing only IOFormatPlugins""" 

156 return cast( 

157 PluginCollection[IOFormatPlugin], self.by_type[IOFormatPlugin] 

158 ) 

159 

160 @property 

161 def viewers(self) -> PluginCollection[ViewerPlugin]: 

162 """Get a PluginCollection containing only ViewerPlugins""" 

163 return cast(PluginCollection[ViewerPlugin], self.by_type[ViewerPlugin]) 

164 

165 def display(self) -> str: 

166 return '\n'.join(sorted(plugin.display() for plugin in self))