Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

# 

# LSST Data Management System 

# Copyright 2008, 2009, 2010 LSST Corporation. 

# 

# This product includes software developed by the 

# LSST Project (http://www.lsst.org/). 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# 

# This program is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the LSST License Statement and 

# the GNU General Public License along with this program. If not, 

# see <http://www.lsstcorp.org/LegalNotices/>. 

# 

 

__all__ = ("Registry", "makeRegistry", "RegistryField", "registerConfig", "registerConfigurable") 

 

import collections.abc 

import copy 

 

from .config import Config, FieldValidationError, _typeStr 

from .configChoiceField import ConfigInstanceDict, ConfigChoiceField 

 

 

class ConfigurableWrapper: 

"""A wrapper for configurables 

 

Used for configurables that don't contain a ConfigClass attribute, 

or contain one that is being overridden. 

""" 

def __init__(self, target, ConfigClass): 

self.ConfigClass = ConfigClass 

self._target = target 

 

def __call__(self, *args, **kwargs): 

return self._target(*args, **kwargs) 

 

 

class Registry(collections.abc.Mapping): 

"""A base class for global registries, mapping names to configurables. 

 

There are no hard requirements on configurable, but they typically create an algorithm 

or are themselves the algorithm, and typical usage is as follows: 

- configurable is a callable whose call signature is (config, ...extra arguments...) 

- All configurables added to a particular registry will have the same call signature 

- All configurables in a registry will typically share something important in common. 

For example all configurables in psfMatchingRegistry return a psf matching 

class that has a psfMatch method with a particular call signature. 

 

A registry acts like a read-only dictionary with an additional register method to add items. 

The dict contains configurables and each configurable has an instance ConfigClass. 

 

Example: 

registry = Registry() 

class FooConfig(Config): 

val = Field(dtype=int, default=3, doc="parameter for Foo") 

class Foo: 

ConfigClass = FooConfig 

def __init__(self, config): 

self.config = config 

def addVal(self, num): 

return self.config.val + num 

registry.register("foo", Foo) 

names = registry.keys() # returns ("foo",) 

fooConfigurable = registry["foo"] 

fooConfig = fooItem.ConfigClass() 

foo = fooConfigurable(fooConfig) 

foo.addVal(5) # returns config.val + 5 

""" 

 

def __init__(self, configBaseType=Config): 

"""Construct a registry of name: configurables 

 

@param configBaseType: base class for config classes in registry 

""" 

if not issubclass(configBaseType, Config): 

raise TypeError("configBaseType=%s must be a subclass of Config" % _typeStr(configBaseType,)) 

self._configBaseType = configBaseType 

self._dict = {} 

 

def register(self, name, target, ConfigClass=None): 

"""Add a new item to the registry. 

 

@param target A callable 'object that takes a Config instance as its first argument. 

This may be a Python type, but is not required to be. 

@param ConfigClass A subclass of pex_config Config used to configure the configurable; 

if None then configurable.ConfigClass is used. 

 

@note: If ConfigClass is provided then then 'target' is wrapped in a new object that forwards 

function calls to it. Otherwise the original 'target' is stored. 

 

@raise AttributeError if ConfigClass is None and target does not have attribute ConfigClass 

""" 

if name in self._dict: 

raise RuntimeError("An item with name %r already exists" % name) 

if ConfigClass is None: 

wrapper = target 

else: 

wrapper = ConfigurableWrapper(target, ConfigClass) 

if not issubclass(wrapper.ConfigClass, self._configBaseType): 

raise TypeError("ConfigClass=%s is not a subclass of %r" % 

(_typeStr(wrapper.ConfigClass), _typeStr(self._configBaseType))) 

self._dict[name] = wrapper 

 

def __getitem__(self, key): 

return self._dict[key] 

 

def __len__(self): 

return len(self._dict) 

 

def __iter__(self): 

return iter(self._dict) 

 

def __contains__(self, key): 

return key in self._dict 

 

def makeField(self, doc, default=None, optional=False, multi=False): 

return RegistryField(doc, self, default, optional, multi) 

 

 

class RegistryAdaptor(collections.abc.Mapping): 

"""Private class that makes a Registry behave like the thing a ConfigChoiceField expects.""" 

 

def __init__(self, registry): 

self.registry = registry 

 

def __getitem__(self, k): 

return self.registry[k].ConfigClass 

 

def __iter__(self): 

return iter(self.registry) 

 

def __len__(self): 

return len(self.registry) 

 

def __contains__(self, k): 

return k in self.registry 

 

 

class RegistryInstanceDict(ConfigInstanceDict): 

def __init__(self, config, field): 

ConfigInstanceDict.__init__(self, config, field) 

self.registry = field.registry 

 

def _getTarget(self): 

if self._field.multi: 

raise FieldValidationError(self._field, self._config, 

"Multi-selection field has no attribute 'target'") 

return self._field.typemap.registry[self._selection] 

target = property(_getTarget) 

 

def _getTargets(self): 

if not self._field.multi: 

raise FieldValidationError(self._field, self._config, 

"Single-selection field has no attribute 'targets'") 

return [self._field.typemap.registry[c] for c in self._selection] 

targets = property(_getTargets) 

 

def apply(self, *args, **kw): 

"""Call the active target(s) with the active config as a keyword arg 

 

If this is a multi-selection field, return a list obtained by calling 

each active target with its corresponding active config. 

 

Additional arguments will be passed on to the configurable target(s) 

""" 

if self.active is None: 

msg = "No selection has been made. Options: %s" % \ 

(" ".join(list(self._field.typemap.registry.keys()))) 

raise FieldValidationError(self._field, self._config, msg) 

if self._field.multi: 

retvals = [] 

for c in self._selection: 

retvals.append(self._field.typemap.registry[c](*args, config=self[c], **kw)) 

return retvals 

else: 

return self._field.typemap.registry[self.name](*args, config=self[self.name], **kw) 

 

def __setattr__(self, attr, value): 

if attr == "registry": 

object.__setattr__(self, attr, value) 

else: 

ConfigInstanceDict.__setattr__(self, attr, value) 

 

 

class RegistryField(ConfigChoiceField): 

instanceDictClass = RegistryInstanceDict 

 

def __init__(self, doc, registry, default=None, optional=False, multi=False): 

types = RegistryAdaptor(registry) 

self.registry = registry 

ConfigChoiceField.__init__(self, doc, types, default, optional, multi) 

 

def __deepcopy__(self, memo): 

"""Customize deep-copying, want a reference to the original registry. 

WARNING: this must be overridden by subclasses if they change the 

constructor signature! 

""" 

other = type(self)(doc=self.doc, registry=self.registry, 

default=copy.deepcopy(self.default), 

optional=self.optional, multi=self.multi) 

other.source = self.source 

return other 

 

 

def makeRegistry(doc, configBaseType=Config): 

"""A convenience function to create a new registry. 

 

The returned value is an instance of a trivial subclass of Registry whose only purpose is to 

customize its doc string and set attrList. 

""" 

cls = type("Registry", (Registry,), {"__doc__": doc}) 

return cls(configBaseType=configBaseType) 

 

 

def registerConfigurable(name, registry, ConfigClass=None): 

"""A decorator that adds a class as a configurable in a Registry. 

 

If the 'ConfigClass' argument is None, the class's ConfigClass attribute will be used. 

""" 

def decorate(cls): 

registry.register(name, target=cls, ConfigClass=ConfigClass) 

return cls 

return decorate 

 

 

def registerConfig(name, registry, target): 

"""A decorator that adds a class as a ConfigClass in a Registry, and associates it with the given 

configurable. 

""" 

def decorate(cls): 

registry.register(name, target=target, ConfigClass=cls) 

return cls 

return decorate