Coverage for tests/test_templates.py: 10%

180 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-03-12 10:07 +0000

1# This file is part of daf_butler. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

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

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

7# for details of code ownership. 

8# 

9# This software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

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

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

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

18# (at your option) any later version. 

19# 

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

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

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

23# GNU General Public License for more details. 

24# 

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

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

27 

28"""Test file name templating.""" 

29 

30import os.path 

31import unittest 

32import uuid 

33 

34from lsst.daf.butler import ( 

35 DataCoordinate, 

36 DatasetId, 

37 DatasetRef, 

38 DatasetType, 

39 DimensionUniverse, 

40 StorageClass, 

41) 

42from lsst.daf.butler.datastore.file_templates import ( 

43 FileTemplate, 

44 FileTemplates, 

45 FileTemplatesConfig, 

46 FileTemplateValidationError, 

47) 

48 

49TESTDIR = os.path.abspath(os.path.dirname(__file__)) 

50 

51PlaceHolder = StorageClass("PlaceHolder") 

52 

53REFUUID = DatasetId(int=uuid.uuid4().int) 

54 

55 

56class TestFileTemplates(unittest.TestCase): 

57 """Test creation of paths from templates.""" 

58 

59 def makeDatasetRef( 

60 self, datasetTypeName, dataId=None, storageClassName="DefaultStorageClass", run="run2", conform=True 

61 ): 

62 """Make a simple DatasetRef""" 

63 if dataId is None: 

64 dataId = self.dataId 

65 if "physical_filter" in dataId and "band" not in dataId: 

66 dataId["band"] = "b" # Add fake band. 

67 dimensions = self.universe.conform(dataId.keys()) 

68 dataId = DataCoordinate.standardize(dataId, dimensions=dimensions) 

69 

70 # Pretend we have a parent if this looks like a composite 

71 compositeName, componentName = DatasetType.splitDatasetTypeName(datasetTypeName) 

72 parentStorageClass = PlaceHolder if componentName else None 

73 

74 datasetType = DatasetType( 

75 datasetTypeName, 

76 dimensions, 

77 StorageClass(storageClassName), 

78 parentStorageClass=parentStorageClass, 

79 ) 

80 return DatasetRef(datasetType, dataId, id=REFUUID, run=run, conform=conform) 

81 

82 def setUp(self): 

83 self.universe = DimensionUniverse() 

84 self.dataId = { 

85 "instrument": "dummy", 

86 "visit": 52, 

87 "physical_filter": "Most Amazing U Filter Ever", 

88 "day_obs": 20200101, 

89 } 

90 

91 def assertTemplate(self, template, answer, ref): 

92 fileTmpl = FileTemplate(template) 

93 path = fileTmpl.format(ref) 

94 self.assertEqual(path, answer) 

95 

96 def testBasic(self): 

97 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}" 

98 self.assertTemplate( 

99 tmplstr, 

100 "run2/calexp/00052/Most_Amazing_U_Filter_Ever", 

101 self.makeDatasetRef("calexp"), 

102 ) 

103 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail" 

104 self.assertTemplate( 

105 tmplstr, 

106 "run2/calexp/00052/Most_Amazing_U_Filter_Ever-trail", 

107 self.makeDatasetRef("calexp"), 

108 ) 

109 

110 tmplstr = "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail-{run}" 

111 self.assertTemplate( 

112 tmplstr, 

113 "run2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run2", 

114 self.makeDatasetRef("calexp"), 

115 ) 

116 self.assertTemplate( 

117 tmplstr, 

118 "run_2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run_2", 

119 self.makeDatasetRef("calexp", run="run/2"), 

120 ) 

121 

122 # Check that the id is sufficient without any other information. 

123 self.assertTemplate("{id}", str(REFUUID), self.makeDatasetRef("calexp", run="run2")) 

124 

125 self.assertTemplate("{run}/{id}", f"run2/{str(REFUUID)}", self.makeDatasetRef("calexp", run="run2")) 

126 

127 self.assertTemplate( 

128 "fixed/{id}", 

129 f"fixed/{str(REFUUID)}", 

130 self.makeDatasetRef("calexp", run="run2"), 

131 ) 

132 

133 self.assertTemplate( 

134 "fixed/{id}_{physical_filter}", 

135 f"fixed/{str(REFUUID)}_Most_Amazing_U_Filter_Ever", 

136 self.makeDatasetRef("calexp", run="run2"), 

137 ) 

138 

139 # Retain any "/" in run 

140 tmplstr = "{run:/}/{datasetType}/{visit:05d}/{physical_filter}-trail-{run}" 

141 self.assertTemplate( 

142 tmplstr, 

143 "run/2/calexp/00052/Most_Amazing_U_Filter_Ever-trail-run_2", 

144 self.makeDatasetRef("calexp", run="run/2"), 

145 ) 

146 

147 # Check that "." are replaced in the file basename, but not directory. 

148 dataId = {"instrument": "dummy", "visit": 52, "physical_filter": "g.10", "day_obs": 20250101} 

149 self.assertTemplate( 

150 tmplstr, 

151 "run.2/calexp/00052/g_10-trail-run_2", 

152 self.makeDatasetRef("calexp", run="run.2", dataId=dataId), 

153 ) 

154 

155 with self.assertRaises(FileTemplateValidationError): 

156 FileTemplate("no fields at all") 

157 

158 with self.assertRaises(FileTemplateValidationError): 

159 FileTemplate("{visit}") 

160 

161 with self.assertRaises(FileTemplateValidationError): 

162 FileTemplate("{run}_{datasetType}") 

163 

164 with self.assertRaises(FileTemplateValidationError): 

165 FileTemplate("{id}/fixed") 

166 

167 with self.assertRaises(FileTemplateValidationError): 

168 FileTemplate("{run}/../{datasetType}_{visit}") 

169 

170 def testRunOrCollectionNeeded(self): 

171 tmplstr = "{datasetType}/{visit:05d}/{physical_filter}" 

172 with self.assertRaises(FileTemplateValidationError): 

173 self.assertTemplate(tmplstr, "run2/calexp/00052/U", self.makeDatasetRef("calexp")) 

174 

175 def testNoRecord(self): 

176 # Attaching records is not possible in this test code but we can check 

177 # that a missing record when a metadata entry has been requested 

178 # does fail. 

179 tmplstr = "{run}/{datasetType}/{visit.name}/{physical_filter}" 

180 with self.assertRaises(RuntimeError) as cm: 

181 self.assertTemplate(tmplstr, "", self.makeDatasetRef("calexp")) 

182 self.assertIn("No metadata", str(cm.exception)) 

183 

184 def testOptional(self): 

185 """Optional units in templates.""" 

186 ref = self.makeDatasetRef("calexp") 

187 tmplstr = "{run}/{datasetType}/v{visit:05d}_f{physical_filter:?}_{skypix:?}" 

188 self.assertTemplate( 

189 tmplstr, 

190 "run2/calexp/v00052_fMost_Amazing_U_Filter_Ever", 

191 self.makeDatasetRef("calexp"), 

192 ) 

193 

194 du = {"visit": 48, "tract": 265, "skymap": "big", "instrument": "dummy", "htm7": 12345} 

195 self.assertTemplate(tmplstr, "run2/calexpT/v00048_12345", self.makeDatasetRef("calexpT", du)) 

196 

197 # Ensure that this returns a relative path even if the first field 

198 # is optional 

199 tmplstr = "{run}/{tract:?}/{visit:?}/f{physical_filter}" 

200 self.assertTemplate(tmplstr, "run2/52/fMost_Amazing_U_Filter_Ever", ref) 

201 

202 # Ensure that // from optionals are converted to singles 

203 tmplstr = "{run}/{datasetType}/{patch:?}/{tract:?}/f{physical_filter}" 

204 self.assertTemplate(tmplstr, "run2/calexp/fMost_Amazing_U_Filter_Ever", ref) 

205 

206 # Optionals with some text between fields 

207 tmplstr = "{run}/{datasetType}/p{patch:?}_t{tract:?}/f{physical_filter}" 

208 self.assertTemplate(tmplstr, "run2/calexp/p/fMost_Amazing_U_Filter_Ever", ref) 

209 tmplstr = "{run}/{datasetType}/p{patch:?}_t{visit:04d?}/f{physical_filter}" 

210 self.assertTemplate(tmplstr, "run2/calexp/p_t0052/fMost_Amazing_U_Filter_Ever", ref) 

211 

212 def testComponent(self): 

213 """Test handling of components in templates.""" 

214 refMetricOutput = self.makeDatasetRef("metric.output") 

215 refMetric = self.makeDatasetRef("metric") 

216 refMaskedImage = self.makeDatasetRef("calexp.maskedimage.variance") 

217 refWcs = self.makeDatasetRef("calexp.wcs") 

218 

219 tmplstr = "{run}_c_{component}_v{visit}" 

220 self.assertTemplate(tmplstr, "run2_c_output_v52", refMetricOutput) 

221 

222 # We want this template to have both a directory and basename, to 

223 # test that the right parts of the output are replaced. 

224 tmplstr = "{component:?}/{run}_{component:?}_{visit}" 

225 self.assertTemplate(tmplstr, "run2_52", refMetric) 

226 self.assertTemplate(tmplstr, "output/run2_output_52", refMetricOutput) 

227 self.assertTemplate(tmplstr, "maskedimage.variance/run2_maskedimage_variance_52", refMaskedImage) 

228 self.assertTemplate(tmplstr, "output/run2_output_52", refMetricOutput) 

229 

230 # Providing a component but not using it 

231 tmplstr = "{run}/{datasetType}/v{visit:05d}" 

232 with self.assertRaises(KeyError): 

233 self.assertTemplate(tmplstr, "", refWcs) 

234 

235 def testFields(self): 

236 # Template, mandatory fields, optional non-special fields, 

237 # special fields, optional special fields 

238 testData = ( 

239 ( 

240 "{run}/{datasetType}/{visit:05d}/{physical_filter}-trail", 

241 {"visit", "physical_filter"}, 

242 set(), 

243 {"run", "datasetType"}, 

244 set(), 

245 ), 

246 ( 

247 "{run}/{component:?}_{visit}", 

248 {"visit"}, 

249 set(), 

250 {"run"}, 

251 {"component"}, 

252 ), 

253 ( 

254 "{run}/{component:?}_{visit:?}_{physical_filter}_{instrument}_{datasetType}", 

255 {"physical_filter", "instrument"}, 

256 {"visit"}, 

257 {"run", "datasetType"}, 

258 {"component"}, 

259 ), 

260 ) 

261 for tmplstr, mandatory, optional, special, optionalSpecial in testData: 

262 with self.subTest(template=tmplstr): 

263 tmpl = FileTemplate(tmplstr) 

264 fields = tmpl.fields() 

265 self.assertEqual(fields, mandatory) 

266 fields = tmpl.fields(optionals=True) 

267 self.assertEqual(fields, mandatory | optional) 

268 fields = tmpl.fields(specials=True) 

269 self.assertEqual(fields, mandatory | special) 

270 fields = tmpl.fields(specials=True, optionals=True) 

271 self.assertEqual(fields, mandatory | special | optional | optionalSpecial) 

272 

273 def testSimpleConfig(self): 

274 """Test reading from config file""" 

275 configRoot = os.path.join(TESTDIR, "config", "templates") 

276 config1 = FileTemplatesConfig(os.path.join(configRoot, "templates-nodefault.yaml")) 

277 templates = FileTemplates(config1, universe=self.universe) 

278 ref = self.makeDatasetRef("calexp") 

279 tmpl = templates.getTemplate(ref) 

280 self.assertIsInstance(tmpl, FileTemplate) 

281 

282 # This config file should not allow defaulting 

283 ref2 = self.makeDatasetRef("unknown") 

284 with self.assertRaises(KeyError): 

285 templates.getTemplate(ref2) 

286 

287 # This should fall through the datasetTypeName check and use 

288 # StorageClass instead 

289 ref3 = self.makeDatasetRef("unknown2", storageClassName="StorageClassX") 

290 tmplSc = templates.getTemplate(ref3) 

291 self.assertIsInstance(tmplSc, FileTemplate) 

292 

293 # Try with a component: one with defined formatter and one without 

294 refWcs = self.makeDatasetRef("calexp.wcs") 

295 refImage = self.makeDatasetRef("calexp.image") 

296 tmplCalexp = templates.getTemplate(ref) 

297 tmplWcs = templates.getTemplate(refWcs) # Should be special 

298 tmpl_image = templates.getTemplate(refImage) 

299 self.assertIsInstance(tmplCalexp, FileTemplate) 

300 self.assertIsInstance(tmpl_image, FileTemplate) 

301 self.assertIsInstance(tmplWcs, FileTemplate) 

302 self.assertEqual(tmplCalexp, tmpl_image) 

303 self.assertNotEqual(tmplCalexp, tmplWcs) 

304 

305 # Check dimensions lookup order. 

306 # The order should be: dataset type name, dimension, storage class 

307 # This one will not match name but might match storage class. 

308 # It should match dimensions 

309 refDims = self.makeDatasetRef( 

310 "nomatch", dataId={"instrument": "LSST", "physical_filter": "z"}, storageClassName="StorageClassX" 

311 ) 

312 tmplDims = templates.getTemplate(refDims) 

313 self.assertIsInstance(tmplDims, FileTemplate) 

314 self.assertNotEqual(tmplDims, tmplSc) 

315 

316 # Test that instrument overrides retrieve specialist templates 

317 refPvi = self.makeDatasetRef("pvi") 

318 refPviHsc = self.makeDatasetRef("pvi", dataId={"instrument": "HSC", "physical_filter": "z"}) 

319 refPviLsst = self.makeDatasetRef("pvi", dataId={"instrument": "LSST", "physical_filter": "z"}) 

320 

321 tmplPvi = templates.getTemplate(refPvi) 

322 tmplPviHsc = templates.getTemplate(refPviHsc) 

323 tmplPviLsst = templates.getTemplate(refPviLsst) 

324 self.assertEqual(tmplPvi, tmplPviLsst) 

325 self.assertNotEqual(tmplPvi, tmplPviHsc) 

326 

327 # Have instrument match and dimensions look up with no name match 

328 refNoPviHsc = self.makeDatasetRef( 

329 "pvix", dataId={"instrument": "HSC", "physical_filter": "z"}, storageClassName="StorageClassX" 

330 ) 

331 tmplNoPviHsc = templates.getTemplate(refNoPviHsc) 

332 self.assertNotEqual(tmplNoPviHsc, tmplDims) 

333 self.assertNotEqual(tmplNoPviHsc, tmplPviHsc) 

334 

335 # Format config file with defaulting 

336 config2 = FileTemplatesConfig(os.path.join(configRoot, "templates-withdefault.yaml")) 

337 templates = FileTemplates(config2, universe=self.universe) 

338 tmpl = templates.getTemplate(ref2) 

339 self.assertIsInstance(tmpl, FileTemplate) 

340 

341 # Format config file with bad format string 

342 with self.assertRaises(FileTemplateValidationError): 

343 FileTemplates(os.path.join(configRoot, "templates-bad.yaml"), universe=self.universe) 

344 

345 # Config file with no defaulting mentioned 

346 config3 = os.path.join(configRoot, "templates-nodefault2.yaml") 

347 templates = FileTemplates(config3, universe=self.universe) 

348 with self.assertRaises(KeyError): 

349 templates.getTemplate(ref2) 

350 

351 # Try again but specify a default in the constructor 

352 default = "{run}/{datasetType}/{physical_filter}" 

353 templates = FileTemplates(config3, default=default, universe=self.universe) 

354 tmpl = templates.getTemplate(ref2) 

355 self.assertEqual(tmpl.template, default) 

356 

357 def testValidation(self): 

358 configRoot = os.path.join(TESTDIR, "config", "templates") 

359 config1 = FileTemplatesConfig(os.path.join(configRoot, "templates-nodefault.yaml")) 

360 templates = FileTemplates(config1, universe=self.universe) 

361 

362 entities = {} 

363 entities["calexp"] = self.makeDatasetRef( 

364 "calexp", 

365 storageClassName="StorageClassX", 

366 dataId={"instrument": "dummy", "physical_filter": "i", "visit": 52}, 

367 ) 

368 

369 with self.assertLogs(level="WARNING") as cm: 

370 templates.validateTemplates(entities.values(), logFailures=True) 

371 self.assertIn("Unchecked keys", cm.output[0]) 

372 self.assertIn("StorageClassX", cm.output[0]) 

373 

374 entities["pvi"] = self.makeDatasetRef( 

375 "pvi", storageClassName="StorageClassX", dataId={"instrument": "dummy", "physical_filter": "i"} 

376 ) 

377 entities["StorageClassX"] = self.makeDatasetRef( 

378 "storageClass", storageClassName="StorageClassX", dataId={"instrument": "dummy", "visit": 2} 

379 ) 

380 entities["calexp.wcs"] = self.makeDatasetRef( 

381 "calexp.wcs", 

382 storageClassName="StorageClassX", 

383 dataId={"instrument": "dummy", "physical_filter": "i", "visit": 23}, 

384 conform=False, 

385 ) 

386 

387 entities["instrument+physical_filter"] = self.makeDatasetRef( 

388 "filter_inst", 

389 storageClassName="StorageClassX", 

390 dataId={"physical_filter": "i", "instrument": "SCUBA"}, 

391 ) 

392 entities["hsc+pvi"] = self.makeDatasetRef( 

393 "pvi", storageClassName="StorageClassX", dataId={"physical_filter": "i", "instrument": "HSC"} 

394 ) 

395 

396 entities["hsc+instrument+physical_filter"] = self.makeDatasetRef( 

397 "filter_inst", 

398 storageClassName="StorageClassX", 

399 dataId={"physical_filter": "i", "instrument": "HSC"}, 

400 ) 

401 

402 entities["metric6"] = self.makeDatasetRef( 

403 "filter_inst", 

404 storageClassName="Integer", 

405 dataId={"physical_filter": "i", "instrument": "HSC"}, 

406 ) 

407 

408 templates.validateTemplates(entities.values(), logFailures=True) 

409 

410 # Rerun but with a failure 

411 entities["pvi"] = self.makeDatasetRef("pvi", storageClassName="StorageClassX", dataId={"band": "i"}) 

412 with self.assertRaises(FileTemplateValidationError): 

413 with self.assertLogs(level="FATAL"): 

414 templates.validateTemplates(entities.values(), logFailures=True) 

415 

416 

417if __name__ == "__main__": 

418 unittest.main()