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

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

# This file is part of daf_butler. 

# 

# Developed for the LSST Data Management System. 

# This product includes software developed by the LSST Project 

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

# See the COPYRIGHT file at the top-level directory of this distribution 

# for details of code ownership. 

# 

# 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 GNU General Public License 

# along with this program. If not, see <http://www.gnu.org/licenses/>. 

 

"""Support for reading and writing composite objects.""" 

 

import collections 

 

 

class DatasetComponent: 

 

"""Component of a dataset and associated information. 

 

Parameters 

---------- 

name : `str` 

Name of the component. 

storageClass : `StorageClass` 

StorageClass to be used when reading or writing this component. 

component : `object` 

Component extracted from the composite object. 

 

""" 

 

def __init__(self, name, storageClass, component): 

self.name = name 

self.storageClass = storageClass 

self.component = component 

 

 

class CompositeAssembler: 

"""Class for providing assembler and disassembler support for composites. 

 

Attributes 

---------- 

storageClass : `StorageClass` 

 

Parameters 

---------- 

storageClass : `StorageClass` 

`StorageClass` to be used with this assembler. 

""" 

 

def __init__(self, storageClass): 

self.storageClass = storageClass 

 

@staticmethod 

def _attrNames(componentName, getter=True): 

"""Return list of suitable attribute names to attempt to use. 

 

Parameters 

---------- 

componentName : `str` 

Name of component/attribute to look for. 

getter : `bool` 

If true, return getters, else return setters. 

 

Returns 

------- 

attrs : `tuple(str)` 

Tuple of strings to attempt. 

""" 

root = "get" if getter else "set" 

 

# Capitalized name for getXxx must only capitalize first letter and not 

# downcase the rest. getVisitInfo and not getVisitinfo 

first = componentName[0].upper() 

85 ↛ 88line 85 didn't jump to line 88, because the condition on line 85 was never false if len(componentName) > 1: 

tail = componentName[1:] 

else: 

tail = "" 

capitalized = "{}{}{}".format(root, first, tail) 

return (componentName, "{}_{}".format(root, componentName), capitalized) 

 

def assemble(self, components, pytype=None): 

"""Construct an object from components based on storageClass. 

 

This generic implementation assumes that instances of objects 

can be created either by passing all the components to a constructor 

or by calling setter methods with the name. 

 

Parameters 

---------- 

components : `dict` 

Collection of components from which to assemble a new composite 

object. Keys correspond to composite names in the `StorageClass`. 

pytype : `type`, optional 

Override the type from the :attr:`CompositeAssembler.storageClass` 

to use when assembling the final object. 

 

Returns 

------- 

composite : `object` 

New composite object assembled from components. 

 

Raises 

------ 

ValueError 

Some components could not be used to create the object or, 

alternatively, some components were not defined in the associated 

StorageClass. 

""" 

if pytype is not None: 

cls = pytype 

else: 

cls = self.storageClass.pytype 

 

# Check that the storage class components are consistent 

understood = set(self.storageClass.components) 

requested = set(components.keys()) 

unknown = requested - understood 

129 ↛ 130line 129 didn't jump to line 130, because the condition on line 129 was never true if unknown: 

raise ValueError("Requested component(s) not known to StorageClass: {}".format(unknown)) 

 

# First try to create an instance directly using keyword args 

try: 

obj = cls(**components) 

except TypeError: 

obj = None 

 

# Now try to use setters if direct instantiation didn't work 

139 ↛ 140line 139 didn't jump to line 140, because the condition on line 139 was never true if not obj: 

obj = cls() 

 

failed = [] 

for name, component in components.items(): 

if component is None: 

continue 

for attr in self._attrNames(name, getter=False): 

if hasattr(obj, attr): 

if attr == name: # Real attribute 

setattr(obj, attr, component) 

else: 

setter = getattr(obj, attr) 

setter(component) 

break 

else: 

failed.append(name) 

 

if failed: 

raise ValueError("Unhandled components during assembly ({})".format(failed)) 

 

return obj 

 

def getValidComponents(self, composite): 

"""Extract all non-None components from a composite. 

 

Parameters 

---------- 

composite : `object` 

Composite from which to extract components. 

 

Returns 

------- 

comps : `dict` 

Non-None components extracted from the composite, indexed by the 

component name as derived from the 

`CompositeAssembler.storageClass`. 

""" 

components = {} 

if self.storageClass is not None and self.storageClass.components: 

for c in self.storageClass.components: 

if isinstance(composite, collections.Mapping): 

comp = composite[c] 

else: 

try: 

comp = self.getComponent(composite, c) 

except AttributeError: 

pass 

else: 

if comp is not None: 

components[c] = comp 

return components 

 

def getComponent(self, composite, componentName): 

"""Attempt to retrieve component from composite object by heuristic. 

 

Will attempt a direct attribute retrieval, or else getter methods of 

the form "get_componentName" and "getComponentName". 

 

Parameters 

---------- 

composite : `object` 

Item to query for the component. 

componentName : `str` 

Name of component to retrieve. 

 

Returns 

------- 

component : `object` 

Component extracted from composite. 

 

Raises 

------ 

AttributeError 

The attribute could not be read from the composite. 

""" 

component = None 

 

if hasattr(composite, "__contains__") and componentName in composite: 

component = composite[componentName] 

return component 

 

221 ↛ 228line 221 didn't jump to line 228, because the loop on line 221 didn't complete for attr in self._attrNames(componentName, getter=True): 

if hasattr(composite, attr): 

component = getattr(composite, attr) 

if attr != componentName: # We have a method 

component = component() 

break 

else: 

raise AttributeError("Unable to get component {}".format(componentName)) 

return component 

 

def disassemble(self, composite, subset=None, override=None): 

"""Generic implementation of a disassembler. 

 

This implementation attempts to extract components from the parent 

by looking for attributes of the same name or getter methods derived 

from the component name. 

 

Parameters 

---------- 

composite : `object` 

Parent composite object consisting of components to be extracted. 

subset : iterable, optional 

Iterable containing subset of components to extract from composite. 

Must be a subset of those defined in 

`CompositeAssembler.storageClass`. 

override : `object`, optional 

Object to use for disassembly instead of parent. This can be useful 

when called from subclasses that have composites in a hierarchy. 

 

Returns 

------- 

components : `dict` 

`dict` with keys matching the components defined in 

`CompositeAssembler.storageClass` 

and values being `DatasetComponent` instances describing the 

component. Returns None if this is not a composite 

`CompositeAssembler.storageClass`. 

 

Raises 

------ 

ValueError 

A requested component can not be found in the parent using generic 

lookups. 

TypeError 

The parent object does not match the supplied 

`CompositeAssembler.storageClass`. 

""" 

268 ↛ 269line 268 didn't jump to line 269, because the condition on line 268 was never true if self.storageClass.components is None: 

return 

 

271 ↛ 272line 271 didn't jump to line 272, because the condition on line 271 was never true if not self.storageClass.validateInstance(composite): 

raise TypeError("Unexpected type mismatch between parent and StorageClass" 

" ({} != {})".format(type(composite), self.storageClass.pytype)) 

 

requested = set(self.storageClass.components) 

 

if subset is not None: 

subset = set(subset) 

diff = subset - requested 

280 ↛ 281line 280 didn't jump to line 281, because the condition on line 280 was never true if diff: 

raise ValueError("Requested subset is not a subset of supported components: {}".format(diff)) 

requested = subset 

 

if override is not None: 

composite = override 

 

components = {} 

for c in list(requested): 

# Try three different ways to get a value associated with the 

# component name. 

try: 

component = self.getComponent(composite, c) 

except AttributeError: 

# Defer complaining so we get an idea of how many problems we have 

pass 

else: 

# If we found a match store it in the results dict and remove 

# it from the list of components we are still looking for. 

if component is not None: 

components[c] = DatasetComponent(c, self.storageClass.components[c], component) 

requested.remove(c) 

 

303 ↛ 304line 303 didn't jump to line 304, because the condition on line 303 was never true if requested: 

raise ValueError("Unhandled components during disassembly ({})".format(requested)) 

 

return components 

 

 

class CompositeAssemblerMonolithic(CompositeAssembler): 

"""Generic assembler class that disables disassembly.""" 

disassemble = None