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

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

# 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 file template string expansion.""" 

 

__all__ = ("FileTemplates", "FileTemplate", "FileTemplatesConfig", "FileTemplateValidationError") 

 

import os.path 

import string 

import logging 

from types import MappingProxyType 

 

from .config import Config 

from .configSupport import processLookupConfigs, LookupKey 

from .exceptions import ValidationError 

from .dimensions import SkyPixDimension, DataCoordinate 

 

log = logging.getLogger(__name__) 

 

 

class FileTemplateValidationError(ValidationError): 

"""Exception thrown when a file template is not consistent with the 

associated `DatasetType`.""" 

pass 

 

 

class FileTemplatesConfig(Config): 

"""Configuration information for `FileTemplates`""" 

pass 

 

 

class FileTemplates: 

"""Collection of `FileTemplate` templates. 

 

Parameters 

---------- 

config : `FileTemplatesConfig` or `str` 

Load configuration. 

default : `str`, optional 

If not `None`, a default template to use if no template has 

been specified explicitly in the configuration. 

universe : `DimensionUniverse` 

The set of all known dimensions, used to normalize any lookup keys 

involving dimensions. 

 

Notes 

----- 

The configuration can include one level of hierarchy where an 

instrument-specific section can be defined to override more general 

template specifications. This is represented in YAML using a 

key of form ``instrument<name>`` which can then define templates 

that will be returned if a `DatasetRef` contains a matching instrument 

name in the data ID. 

 

A default fallback template can be specified using the key ``default``. 

Defaulting can be disabled in a child configuration by defining the 

value to be an empty string or a boolean `False`. 

 

The config is parsed using the function 

`~lsst.daf.butler.configSubset.processLookupConfigs`. 

""" 

 

defaultKey = LookupKey("default") 

"""Configuration key associated with the default template.""" 

 

def __init__(self, config, default=None, *, universe): 

self.config = FileTemplatesConfig(config) 

self._templates = {} 

self.default = FileTemplate(default) if default is not None else None 

contents = processLookupConfigs(self.config, universe=universe) 

 

# Convert all the values to FileTemplate, handling defaults 

for key, templateStr in contents.items(): 

if key == self.defaultKey: 

if not templateStr: 

self.default = None 

else: 

self.default = FileTemplate(templateStr) 

else: 

self._templates[key] = FileTemplate(templateStr) 

 

@property 

def templates(self): 

"""Collection of templates indexed by lookup key (`dict`).""" 

return MappingProxyType(self._templates) 

 

def __contains__(self, key): 

"""Indicates whether the supplied key is present in the templates. 

 

Parameters 

---------- 

key : `LookupKey` 

Key to use to determine if a corresponding value is present 

in the templates. 

 

Returns 

------- 

in : `bool` 

`True` if the supplied key is present in the templates. 

""" 

return key in self.templates 

 

def __getitem__(self, key): 

return self.templates[key] 

 

def validateTemplates(self, entities, logFailures=False): 

"""Retrieve the template associated with each dataset type and 

validate the dimensions against the template. 

 

Parameters 

---------- 

entities : `DatasetType`, `DatasetRef`, or `StorageClass` 

Entities to validate against the matching templates. Can be 

differing types. 

logFailures : `bool`, optional 

If `True`, output a log message for every validation error 

detected. 

 

Raises 

------ 

FileTemplateValidationError 

Raised if an entity failed validation. 

 

Notes 

----- 

See `FileTemplate.validateTemplate()` for details on the validation. 

""" 

unmatchedKeys = set(self.templates) 

failed = [] 

for entity in entities: 

try: 

matchKey, template = self.getTemplateWithMatch(entity) 

except KeyError as e: 

# KeyError always quotes on stringification so strip here 

errMsg = str(e).strip('"\'') 

failed.append(errMsg) 

if logFailures: 

log.fatal("%s", errMsg) 

continue 

 

if matchKey in unmatchedKeys: 

unmatchedKeys.remove(matchKey) 

 

try: 

template.validateTemplate(entity) 

except FileTemplateValidationError as e: 

failed.append(f"{e} (via key '{matchKey}')") 

if logFailures: 

log.fatal("Template failure with key '%s': %s", matchKey, e) 

 

if logFailures and unmatchedKeys: 

log.warning("Unchecked keys: %s", ", ".join([str(k) for k in unmatchedKeys])) 

 

if failed: 

if len(failed) == 1: 

msg = str(failed[0]) 

else: 

failMsg = ";\n".join(failed) 

msg = f"{len(failed)} template validation failures: {failMsg}" 

raise FileTemplateValidationError(msg) 

 

def getLookupKeys(self): 

"""Retrieve the look up keys for all the template entries. 

 

Returns 

------- 

keys : `set` of `LookupKey` 

The keys available for matching a template. 

""" 

return set(self.templates) 

 

def getTemplateWithMatch(self, entity): 

"""Retrieve the `FileTemplate` associated with the dataset type along 

with the lookup key that was a match for this template. 

 

If the lookup name corresponds to a component the base name for 

the component will be examined if the full component name does 

not match. 

 

Parameters 

---------- 

entity : `DatasetType`, `DatasetRef`, or `StorageClass` 

Instance to use to look for a corresponding template. 

A `DatasetType` name or a `StorageClass` name will be used 

depending on the supplied entity. Priority is given to a 

`DatasetType` name. Supports instrument override if a 

`DatasetRef` is provided configured with an ``instrument`` 

value for the data ID. 

 

Returns 

------- 

matchKey : `LookupKey` 

The key that resulted in the successful match. 

template : `FileTemplate` 

Template instance to use with that dataset type. 

 

Raises 

------ 

KeyError 

Raised if no template could be located for this Dataset type. 

""" 

# Get the names to use for lookup 

names = entity._lookupNames() 

 

# Get a location from the templates 

template = self.default 

source = self.defaultKey 

for name in names: 

if name in self.templates: 

template = self.templates[name] 

source = name 

break 

 

if template is None: 

raise KeyError(f"Unable to determine file template from supplied argument [{entity}]") 

 

log.debug("Got file %s from %s via %s", template, entity, source) 

 

return source, template 

 

def getTemplate(self, entity): 

"""Retrieve the `FileTemplate` associated with the dataset type. 

 

If the lookup name corresponds to a component the base name for 

the component will be examined if the full component name does 

not match. 

 

Parameters 

---------- 

entity : `DatasetType`, `DatasetRef`, or `StorageClass` 

Instance to use to look for a corresponding template. 

A `DatasetType` name or a `StorageClass` name will be used 

depending on the supplied entity. Priority is given to a 

`DatasetType` name. Supports instrument override if a 

`DatasetRef` is provided configured with an ``instrument`` 

value for the data ID. 

 

Returns 

------- 

template : `FileTemplate` 

Template instance to use with that dataset type. 

 

Raises 

------ 

KeyError 

Raised if no template could be located for this Dataset type. 

""" 

_, template = self.getTemplateWithMatch(entity) 

return template 

 

 

class FileTemplate: 

"""Format a path template into a fully expanded path. 

 

Parameters 

---------- 

template : `str` 

Template string. 

 

Raises 

------ 

FileTemplateValidationError 

Raised if the template fails basic validation. 

 

Notes 

----- 

The templates use the standard Format Specification Mini-Language 

with the caveat that only named fields can be used. The field names 

are taken from the Dimensions along with several additional fields: 

 

- datasetType: `str`, `DatasetType.name` 

- component: `str`, name of the StorageClass component 

- run: `str`, name of the run this dataset was added with 

- collection: synonoym for ``run`` 

 

At least one of `run` or `collection` must be provided to ensure unique 

filenames. 

 

More detailed information can be requested from dimensions by using a dot 

notation, so ``visit.name`` would use the name of the visit and 

``detector.name_in_raft`` would use the name of the detector within the 

raft. 

 

The mini-language is extended to understand a "?" in the format 

specification. This indicates that a field is optional. If that 

Dimension is missing the field, along with the text before the field, 

unless it is a path separator, will be removed from the output path. 

 

By default any "/" in a dataId value will be replaced by "_" to prevent 

unexpected directories being created in the path. If the "/" should be 

retained then a special "/" format specifier can be included in the 

template. 

""" 

 

mandatoryFields = {"collection", "run"} 

"""A set of fields, one of which must be present in a template.""" 

 

datasetFields = {"datasetType", "component"} 

"""Fields related to the supplied dataset, not a dimension.""" 

 

specialFields = mandatoryFields | datasetFields 

"""Set of special fields that are available independently of the defined 

Dimensions.""" 

 

def __init__(self, template): 

if not isinstance(template, str): 

raise FileTemplateValidationError(f"Template ('{template}') does " 

"not contain any format specifiers") 

self.template = template 

 

# Do basic validation without access to dimensions 

self.validateTemplate(None) 

 

def __eq__(self, other): 

if not isinstance(other, FileTemplate): 

return False 

 

return self.template == other.template 

 

def __str__(self): 

return self.template 

 

def __repr__(self): 

return f'{self.__class__.__name__}("{self.template}")' 

 

def fields(self, optionals=False, specials=False, subfields=False): 

"""Return the field names used in this template. 

 

Parameters 

---------- 

optionals : `bool` 

If `True`, optional fields are included in the returned set. 

specials : `bool` 

If `True`, non-dimension fields are included. 

subfields : `bool`, optional 

If `True`, fields with syntax ``a.b`` are included. If `False`, 

the default, only ``a`` would be returned. 

 

Returns 

------- 

names : `set` 

Names of fields used in this template 

 

Notes 

----- 

The returned set will include the special values such as `datasetType` 

and `component`. 

""" 

fmt = string.Formatter() 

parts = fmt.parse(self.template) 

 

names = set() 

for literal, field_name, format_spec, conversion in parts: 

if field_name is not None: 

if "?" in format_spec and not optionals: 

continue 

 

if not specials and field_name in self.specialFields: 

continue 

 

if "." in field_name and not subfields: 

field_name, _ = field_name.split(".") 

 

names.add(field_name) 

 

return names 

 

def format(self, ref): 

"""Format a template string into a full path. 

 

Parameters 

---------- 

ref : `DatasetRef` 

The dataset to be formatted. 

 

Returns 

------- 

path : `str` 

Expanded path. 

 

Raises 

------ 

KeyError 

Raised if the requested field is not defined and the field is 

not optional. Or, `component` is specified but "component" was 

not part of the template. 

""" 

# Extract defined non-None dimensions from the dataId 

# We attempt to get the "full" dict on the assumption that ref.dataId 

# is a ExpandedDataCoordinate, as it should be when running 

# PipelineTasks. We should probably just require that when formatting 

# templates (and possibly when constructing DatasetRefs), but doing so 

# would break a ton of otherwise-useful tests that would need to be 

# modified to provide a lot more metadata. 

fields = {k: v for k, v in getattr(ref.dataId, "full", ref.dataId).items() if v is not None} 

 

if isinstance(ref.dataId, DataCoordinate): 

# If there is exactly one SkyPixDimension in the data ID, alias its 

# value with the key "skypix", so we can use that to match any 

# skypix dimension. 

# We restrict this behavior to the (real-world) case where the 

# data ID is a DataCoordinate, not just a dict. That should only 

# not be true in some test code, but that test code is a pain to 

# update to be more like the real world while still providing our 

# only tests of important behavior. 

skypix = [dimension for dimension in ref.dataId.graph if isinstance(dimension, SkyPixDimension)] 

if len(skypix) == 1: 

fields["skypix"] = fields[skypix[0]] 

 

# Extra information that can be included using . syntax 

extras = getattr(ref.dataId, "records", {}) 

 

datasetType = ref.datasetType 

fields["datasetType"], component = datasetType.nameAndComponent() 

 

usedComponent = False 

if component is not None: 

fields["component"] = component 

 

usedRunOrCollection = False 

fields["collection"] = ref.run 

fields["run"] = ref.run 

 

fmt = string.Formatter() 

parts = fmt.parse(self.template) 

output = "" 

 

for literal, field_name, format_spec, conversion in parts: 

 

if field_name == "component": 

usedComponent = True 

 

if format_spec is None: 

output = output + literal 

continue 

 

if "?" in format_spec: 

optional = True 

# Remove the non-standard character from the spec 

format_spec = format_spec.replace("?", "") 

else: 

optional = False 

 

if field_name in ("run", "collection"): 

usedRunOrCollection = True 

 

# Check for request for additional information from the dataId 

if "." in field_name: 

primary, secondary = field_name.split(".") 

if primary in extras: 

record = extras[primary] 

# Only fill in the fields if we have a value, the 

# KeyError will trigger below if the attribute is missing. 

if hasattr(record, secondary): 

fields[field_name] = getattr(record, secondary) 

 

if field_name in fields: 

value = fields[field_name] 

elif optional: 

# If this is optional ignore the format spec 

# and do not include the literal text prior to the optional 

# field unless it contains a "/" path separator 

format_spec = "" 

value = "" 

if "/" not in literal: 

literal = "" 

else: 

raise KeyError(f"'{field_name}' requested in template via '{self.template}' " 

"but not defined and not optional") 

 

# Handle "/" in values since we do not want to be surprised by 

# unexpected directories turning up 

replace_slash = True 

if "/" in format_spec: 

# Remove the non-standard character from the spec 

format_spec = format_spec.replace("/", "") 

replace_slash = False 

 

if isinstance(value, str): 

if replace_slash: 

value = value.replace("/", "_") 

 

# Now use standard formatting 

output = output + literal + format(value, format_spec) 

 

# Complain if we were meant to use a component 

if component is not None and not usedComponent: 

raise KeyError("Component '{}' specified but template {} did not use it".format(component, 

self.template)) 

 

# Complain if there's no run or collection 

if not usedRunOrCollection: 

raise KeyError("Template does not include 'run' or 'collection'.") 

 

# Since this is known to be a path, normalize it in case some double 

# slashes have crept in 

path = os.path.normpath(output) 

 

# It should not be an absolute path (may happen with optionals) 

if os.path.isabs(path): 

path = os.path.relpath(path, start="/") 

 

return path 

 

def validateTemplate(self, entity): 

"""Compare the template against a representative entity that would 

like to use template. 

 

Parameters 

---------- 

entity : `DatasetType`, `DatasetRef`, or `StorageClass` 

Entity to compare against template. 

 

Raises 

------ 

FileTemplateValidationError 

Raised if the template is inconsistent with the supplied entity. 

 

Notes 

----- 

Validation will always include a check that mandatory fields 

are present and that at least one field refers to a dimension. 

If the supplied entity includes a `DimensionGraph` then it will be 

used to compare the available dimensions with those specified in the 

template. 

""" 

 

# Check that the template has run or collection 

withSpecials = self.fields(specials=True, optionals=True) 

if not withSpecials & self.mandatoryFields: 

raise FileTemplateValidationError(f"Template '{self}' is missing a mandatory field" 

f" from {self.mandatoryFields}") 

 

# Check that there are some dimension fields in the template 

allfields = self.fields(optionals=True) 

if not allfields: 

raise FileTemplateValidationError(f"Template '{self}' does not seem to have any fields" 

" corresponding to dimensions.") 

 

# If we do not have dimensions available then all we can do is shrug 

if not hasattr(entity, "dimensions"): 

return 

 

# if this entity represents a component then insist that component 

# is present in the template. If the entity is not a component 

# make sure that component is not mandatory. 

try: 

if entity.isComponent(): 

if "component" not in withSpecials: 

raise FileTemplateValidationError(f"Template '{self}' has no component but " 

f"{entity} refers to a component.") 

else: 

mandatorySpecials = self.fields(specials=True) 

if "component" in mandatorySpecials: 

raise FileTemplateValidationError(f"Template '{self}' has mandatory component but " 

f"{entity} does not refer to a component.") 

except AttributeError: 

pass 

 

# Get the dimension links to get the full set of available field names 

# Fall back to dataId keys if we have them but no links. 

# dataId keys must still be present in the template 

try: 

minimal = set(entity.dimensions.required.names) 

maximal = set(entity.dimensions.names) 

except AttributeError: 

try: 

minimal = set(entity.dataId.keys()) 

maximal = minimal 

except AttributeError: 

return 

 

required = self.fields(optionals=False) 

 

# Calculate any field usage that does not match a dimension 

if not required.issubset(maximal): 

raise FileTemplateValidationError(f"Template '{self}' is inconsistent with {entity}:" 

f" {required} is not a subset of {maximal}.") 

 

if not allfields.issuperset(minimal): 

raise FileTemplateValidationError(f"Template '{self}' is inconsistent with {entity}:" 

f" {allfields} is not a superset of {minimal}.") 

 

return