Coverage for python/lsst/ap/verify/workspace.py: 45%

91 statements  

« prev     ^ index     » next       coverage.py v7.2.5, created at 2023-05-13 03:27 -0700

1# 

2# This file is part of ap_verify. 

3# 

4# Developed for the LSST Data Management System. 

5# This product includes software developed by the LSST Project 

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

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

8# for details of code ownership. 

9# 

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

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

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

13# (at your option) any later version. 

14# 

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

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

17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

18# GNU General Public License for more details. 

19# 

20# You should have received a copy of the GNU General Public License 

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

22# 

23 

24__all__ = ["Workspace", "WorkspaceGen3"] 

25 

26import abc 

27import os 

28import pathlib 

29import re 

30import stat 

31 

32import lsst.daf.butler as dafButler 

33import lsst.obs.base as obsBase 

34 

35 

36class Workspace(metaclass=abc.ABCMeta): 

37 """A directory used by ``ap_verify`` to handle data and outputs. 

38 

39 Any object of this class represents a working directory containing 

40 (possibly empty) subdirectories for various purposes. Subclasses are 

41 typically specialized for particular workflows. Keeping such details in 

42 separate classes makes it easier to provide guarantees without forcing 

43 awkward directory structures on users. 

44 

45 All Workspace classes must guarantee the existence of any subdirectories 

46 inside the workspace. Directories corresponding to repositories do not need 

47 to be initialized, since creating a valid repository usually requires 

48 external information. 

49 

50 Parameters 

51 ---------- 

52 location : `str` 

53 The location on disk where the workspace will be set up. Will be 

54 created if it does not already exist. 

55 

56 Raises 

57 ------ 

58 EnvironmentError 

59 Raised if ``location`` is not readable or not writeable 

60 """ 

61 def __init__(self, location): 

62 # Properties must be `str` for backwards compatibility 

63 self._location = str(pathlib.Path(location).resolve()) 

64 

65 self.mkdir(self._location) 

66 self.mkdir(self.configDir) 

67 

68 @staticmethod 

69 def mkdir(directory): 

70 """Create a directory for the workspace. 

71 

72 This method is intended to be called only by subclasses, and should 

73 not be used by external code. 

74 

75 Parameters 

76 ---------- 

77 directory : `str` 

78 The directory to create. 

79 """ 

80 mode = stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH # a+r, u+rwx 

81 pathlib.Path(directory).mkdir(parents=True, exist_ok=True, mode=mode) 

82 

83 def __eq__(self, other): 

84 """Test whether two workspaces are of the same type and have the 

85 same location. 

86 """ 

87 return type(self) == type(other) and self.workDir == other.workDir 

88 

89 def __repr__(self): 

90 """A string representation that can be used to reconstruct the Workspace. 

91 """ 

92 return f"{type(self).__name__}({self.workDir!r})" 

93 

94 @property 

95 def workDir(self): 

96 """The absolute location of the workspace as a whole 

97 (`str`, read-only). 

98 """ 

99 return self._location 

100 

101 @property 

102 def configDir(self): 

103 """The absolute location of a directory containing custom Task config 

104 files for use with the data (`str`, read-only). 

105 """ 

106 return os.path.join(self._location, 'config') 

107 

108 @property 

109 @abc.abstractmethod 

110 def dbLocation(self): 

111 """The default absolute location of the source association database to 

112 be created or updated by the pipeline (`str`, read-only). 

113 

114 Shall be a pathname to a database suitable for the backend of `Apdb`. 

115 """ 

116 

117 @property 

118 @abc.abstractmethod 

119 def alertLocation(self): 

120 """The absolute location of an output directory for persisted 

121 alert packets (`str`, read-only). 

122 """ 

123 

124 @property 

125 @abc.abstractmethod 

126 def workButler(self): 

127 """A Butler that can produce pipeline inputs and outputs (read-only). 

128 The type is class-dependent. 

129 """ 

130 

131 @property 

132 @abc.abstractmethod 

133 def analysisButler(self): 

134 """A Butler that can read pipeline outputs (read-only). 

135 The type is class-dependent. 

136 

137 The Butler should be read-only, if its type supports the restriction. 

138 """ 

139 

140 

141class WorkspaceGen3(Workspace): 

142 """A directory used by ``ap_verify`` to handle data. 

143 

144 Any object of this class represents a working directory containing 

145 subdirectories for a repository and for non-repository files. Constructing 

146 a WorkspaceGen3 does not *initialize* its repository, as this requires 

147 external information. 

148 

149 Parameters 

150 ---------- 

151 location : `str` 

152 The location on disk where the workspace will be set up. Will be 

153 created if it does not already exist. 

154 

155 Raises 

156 ------ 

157 EnvironmentError 

158 Raised if ``location`` is not readable or not writeable 

159 """ 

160 

161 def __init__(self, location): 

162 super().__init__(location) 

163 

164 self.mkdir(self.repo) 

165 self.mkdir(self.pipelineDir) 

166 

167 # Gen 3 name of the output 

168 self.outputName = "ap_verify-output" 

169 

170 # Lazy evaluation to optimize butlers 

171 self._workButler = None 

172 self._analysisButler = None 

173 

174 @property 

175 def repo(self): 

176 """The absolute path/URI to a Butler repo for AP pipeline processing 

177 (`str`, read-only). 

178 """ 

179 return os.path.join(self._location, 'repo') 

180 

181 @property 

182 def pipelineDir(self): 

183 """The absolute location of a directory containing custom pipeline 

184 files for use with the data (`str`, read-only). 

185 """ 

186 return os.path.join(self._location, 'pipelines') 

187 

188 @property 

189 def dbLocation(self): 

190 return os.path.join(self._location, 'association.db') 

191 

192 @property 

193 def alertLocation(self): 

194 return os.path.join(self._location, 'alerts') 

195 

196 def _ensureCollection(self, registry, name, collectionType): 

197 """Add a collection to a repository if it does not already exist. 

198 

199 Parameters 

200 ---------- 

201 registry : `lsst.daf.butler.Registry` 

202 The repository to which to add the collection. 

203 name : `str` 

204 The name of the collection to test for and add. 

205 collectionType : `lsst.daf.butler.CollectionType` 

206 The type of collection to add. This field is ignored when 

207 testing if a collection exists. 

208 """ 

209 matchingCollections = list(registry.queryCollections(re.compile(name))) 

210 if not matchingCollections: 

211 registry.registerCollection(name, type=collectionType) 

212 

213 @property 

214 def workButler(self): 

215 """A Butler that can read and write to a Gen 3 repository (`lsst.daf.butler.Butler`, read-only). 

216 

217 Notes 

218 ----- 

219 Assumes `repo` has been initialized. 

220 """ 

221 if self._workButler is None: 

222 try: 

223 # Dataset generation puts all preloaded datasets in <instrument>/defaults. 

224 # However, this definition excludes raws, which are not preloaded. 

225 queryButler = dafButler.Butler(self.repo, writeable=True) # writeable for _workButler 

226 inputs = [] 

227 for dimension in queryButler.registry.queryDataIds('instrument'): 

228 instrument = obsBase.Instrument.fromName(dimension["instrument"], queryButler.registry) 

229 defaultName = instrument.makeCollectionName("defaults") 

230 inputs.append(defaultName) 

231 rawName = instrument.makeDefaultRawIngestRunName() 

232 inputs.append(rawName) 

233 self._ensureCollection(queryButler.registry, rawName, dafButler.CollectionType.RUN) 

234 

235 # Create an output chain here, so that workButler can see it. 

236 # Definition does not conflict with what pipetask --output uses. 

237 # Regex is workaround for DM-25945. 

238 if not list(queryButler.registry.queryCollections(re.compile(self.outputName))): 

239 queryButler.registry.registerCollection(self.outputName, 

240 dafButler.CollectionType.CHAINED) 

241 queryButler.registry.setCollectionChain(self.outputName, inputs) 

242 

243 self._workButler = dafButler.Butler(butler=queryButler, collections=self.outputName) 

244 except OSError as e: 

245 raise RuntimeError(f"{self.repo} is not a Gen 3 repository") from e 

246 return self._workButler 

247 

248 @property 

249 def analysisButler(self): 

250 """A Butler that can read from a Gen 3 repository with outputs (`lsst.daf.butler.Butler`, read-only). 

251 

252 Notes 

253 ----- 

254 Assumes `repo` has been initialized. 

255 """ 

256 if self._analysisButler is None: 

257 try: 

258 self._analysisButler = dafButler.Butler(self.repo, collections=self.outputName, 

259 writeable=False) 

260 except OSError as e: 

261 raise RuntimeError(f"{self.repo} is not a Gen 3 repository") from e 

262 return self._analysisButler