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

# 

# This file is part of ap_verify. 

# 

# 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/>. 

# 

 

"""Data ingestion for ap_verify. 

 

This module handles ingestion of a dataset into an appropriate repository, so 

that pipeline code need not be aware of the dataset framework. 

""" 

 

__all__ = ["DatasetIngestConfig", "ingestDataset"] 

 

import fnmatch 

import os 

import shutil 

import tarfile 

from contextlib import contextmanager 

from glob import glob 

import sqlite3 

 

import lsst.utils 

import lsst.log 

import lsst.pex.config as pexConfig 

import lsst.pipe.base as pipeBase 

 

from lsst.pipe.tasks.ingest import IngestTask 

from lsst.pipe.tasks.ingestCalibs import IngestCalibsTask 

from lsst.pipe.tasks.ingestDefects import IngestDefectsTask 

 

 

class DatasetIngestConfig(pexConfig.Config): 

"""Settings and defaults for `DatasetIngestTask`. 

 

The correct targets for this task's subtasks can be found in the 

documentation of the appropriate ``obs`` package. 

 

Because `DatasetIngestTask` is not designed to be run from the command line, 

and its arguments are completely determined by the choice of dataset, 

this config includes settings that would normally be passed as command-line 

arguments to `~lsst.pipe.tasks.ingest.IngestTask`. 

""" 

 

dataIngester = pexConfig.ConfigurableField( 

target=IngestTask, 

doc="Task used to perform raw data ingestion.", 

) 

dataFiles = pexConfig.ListField( 

dtype=str, 

default=["*.fits", "*.fz", "*.fits.gz"], 

doc="Names of raw science files (no path; wildcards allowed) to ingest from the dataset.", 

) 

dataBadFiles = pexConfig.ListField( 

dtype=str, 

default=[], 

doc="Names of raw science files (no path; wildcards allowed) to not ingest, " 

"supersedes ``dataFiles``.", 

) 

 

calibIngester = pexConfig.ConfigurableField( 

target=IngestCalibsTask, 

doc="Task used to ingest flats, biases, darks, fringes, or sky.", 

) 

calibFiles = pexConfig.ListField( 

dtype=str, 

default=["*.fits", "*.fz", "*.fits.gz"], 

doc="Names of calib files (no path; wildcards allowed) to ingest from the dataset.", 

) 

calibBadFiles = pexConfig.ListField( 

dtype=str, 

default=[], 

doc="Names of calib files (no path; wildcards allowed) to not ingest, supersedes ``calibFiles``.", 

) 

calibValidity = pexConfig.Field( 

dtype=int, 

default=9999, 

doc="Calibration validity period (days). Assumed equal for all calib types.") 

 

textDefectPath = pexConfig.Field( 

dtype=str, 

default='', 

doc="Path to top level of the defect tree. This is a directory with a directory per sensor." 

) 

defectIngester = pexConfig.ConfigurableField( 

target=IngestDefectsTask, 

doc="Task used to ingest defects.", 

) 

 

refcats = pexConfig.DictField( 

keytype=str, 

itemtype=str, 

default={}, 

doc="Map from a refcat name to a tar.gz file containing the sharded catalog. May be empty.", 

) 

 

 

class DatasetIngestTask(pipeBase.Task): 

"""Task for automating ingestion of a dataset. 

 

Each dataset configures this task as appropriate for the files it provides 

and the target instrument. Therefore, this task takes no input besides the 

dataset to load and the repositories to ingest to. 

""" 

 

ConfigClass = DatasetIngestConfig 

_DefaultName = "datasetIngest" 

 

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

pipeBase.Task.__init__(self, *args, **kwargs) 

self.makeSubtask("dataIngester") 

self.makeSubtask("calibIngester") 

self.makeSubtask("defectIngester") 

 

def run(self, dataset, workspace): 

"""Ingest the contents of a dataset into a Butler repository. 

 

Parameters 

---------- 

dataset : `lsst.ap.verify.dataset.Dataset` 

The dataset to be ingested. 

workspace : `lsst.ap.verify.workspace.Workspace` 

The abstract location where ingestion repositories will be created. 

If the repositories already exist, they must support the same 

``obs`` package as this task's subtasks. 

""" 

# We're assuming ingest tasks always give absolute path to butler 

dataset.makeCompatibleRepo(workspace.dataRepo, os.path.abspath(workspace.calibRepo)) 

self._ingestRaws(dataset, workspace) 

self._ingestCalibs(dataset, workspace) 

self._ingestDefects(dataset, workspace) 

self._ingestRefcats(dataset, workspace) 

self._copyConfigs(dataset, workspace) 

 

def _ingestRaws(self, dataset, workspace): 

"""Ingest the science data for use by LSST. 

 

After this method returns, the data repository in ``workspace`` shall 

contain all science data from ``dataset``. Butler operations on the 

repository shall not be able to modify ``dataset``. 

 

Parameters 

---------- 

dataset : `lsst.ap.verify.dataset.Dataset` 

The dataset on which the pipeline will be run. 

workspace : `lsst.ap.verify.workspace.Workspace` 

The location containing all ingestion repositories. 

 

Raises 

------ 

RuntimeError 

Raised if there are no files to ingest. 

""" 

if os.path.exists(os.path.join(workspace.dataRepo, "registry.sqlite3")): 

self.log.info("Raw images were previously ingested, skipping...") 

else: 

self.log.info("Ingesting raw images...") 

dataFiles = _findMatchingFiles(dataset.rawLocation, self.config.dataFiles) 

if dataFiles: 

self._doIngestRaws(workspace.dataRepo, workspace.calibRepo, 

dataFiles, self.config.dataBadFiles) 

self.log.info("Images are now ingested in {0}".format(workspace.dataRepo)) 

else: 

raise RuntimeError("No raw files found at %s." % dataset.rawLocation) 

 

def _doIngestRaws(self, repo, calibRepo, dataFiles, badFiles): 

"""Ingest raw images into a repository. 

 

``repo`` shall be populated with *links* to ``dataFiles``. 

 

Parameters 

---------- 

repo : `str` 

The output repository location on disk for raw images. Must exist. 

calibRepo : `str` 

The output calibration repository location on disk. 

dataFiles : `list` of `str` 

A list of filenames to ingest. May contain wildcards. 

badFiles : `list` of `str` 

A list of filenames to exclude from ingestion. Must not contain paths. 

May contain wildcards. 

 

Raises 

------ 

RuntimeError 

Raised if ``dataFiles`` is empty. 

""" 

if not dataFiles: 

raise RuntimeError("No raw files to ingest (expected list of filenames, got %r)." % dataFiles) 

 

args = [repo, "--calib", calibRepo, "--mode", "link"] 

args.extend(dataFiles) 

if badFiles: 

args.append('--badFile') 

args.extend(badFiles) 

try: 

_runIngestTask(self.dataIngester, args) 

except sqlite3.IntegrityError as detail: 

raise RuntimeError("Not all raw files are unique") from detail 

 

def _ingestCalibs(self, dataset, workspace): 

"""Ingest the calibration files for use by LSST. 

 

After this method returns, the calibration repository in ``workspace`` 

shall contain all calibration data from ``dataset``. Butler operations 

on the repository shall not be able to modify ``dataset``. 

 

Parameters 

---------- 

dataset : `lsst.ap.verify.dataset.Dataset` 

The dataset on which the pipeline will be run. 

workspace : `lsst.ap.verify.workspace.Workspace` 

The location containing all ingestion repositories. 

 

Raises 

------ 

RuntimeError 

Raised if there are no files to ingest. 

""" 

if os.path.exists(os.path.join(workspace.calibRepo, "calibRegistry.sqlite3")): 

self.log.info("Calibration files were previously ingested, skipping...") 

else: 

self.log.info("Ingesting calibration files...") 

calibDataFiles = _findMatchingFiles(dataset.calibLocation, 

self.config.calibFiles, self.config.calibBadFiles) 

if calibDataFiles: 

self._doIngestCalibs(workspace.dataRepo, workspace.calibRepo, calibDataFiles) 

self.log.info("Calibrations corresponding to {0} are now ingested in {1}".format( 

workspace.dataRepo, workspace.calibRepo)) 

else: 

raise RuntimeError("No calib files found at %s." % dataset.calibLocation) 

 

def _doIngestCalibs(self, repo, calibRepo, calibDataFiles): 

"""Ingest calibration images into a calibration repository. 

 

Parameters 

---------- 

repo : `str` 

The output repository location on disk for raw images. Must exist. 

calibRepo : `str` 

The output repository location on disk for calibration files. Must 

exist. 

calibDataFiles : `list` of `str` 

A list of filenames to ingest. Supported files vary by instrument 

but may include flats, biases, darks, fringes, or sky. May contain 

wildcards. 

 

Raises 

------ 

RuntimeError 

Raised if ``calibDataFiles`` is empty. 

""" 

if not calibDataFiles: 

raise RuntimeError("No calib files to ingest (expected list of filenames, got %r)." 

% calibDataFiles) 

 

# TODO: --output is workaround for DM-11668 

args = [repo, "--calib", calibRepo, "--output", os.path.join(calibRepo, "dummy"), 

"--mode", "link", "--validity", str(self.config.calibValidity)] 

args.extend(calibDataFiles) 

try: 

_runIngestTask(self.calibIngester, args) 

except sqlite3.IntegrityError as detail: 

raise RuntimeError("Not all calibration files are unique") from detail 

 

def _ingestDefects(self, dataset, workspace): 

"""Ingest the defect files for use by LSST. 

 

After this method returns, the calibration repository in ``workspace`` 

shall contain all defects from ``dataset``. Butler operations on the 

repository shall not be able to modify ``dataset``. 

 

Parameters 

---------- 

dataset : `lsst.ap.verify.dataset.Dataset` 

The dataset on which the pipeline will be run. 

workspace : `lsst.ap.verify.workspace.Workspace` 

The location containing all ingestion repositories. 

 

Raises 

------ 

RuntimeError 

Raised if defect ingestion requested but no defects found. 

""" 

if os.path.exists(os.path.join(workspace.calibRepo, "defects")): 

self.log.info("Defects were previously ingested, skipping...") 

else: 

self.log.info("Ingesting defects...") 

self._doIngestDefects(workspace.dataRepo, workspace.calibRepo, self.config.textDefectPath) 

self.log.info("Defects are now ingested in {0}".format(workspace.calibRepo)) 

 

def _doIngestDefects(self, repo, calibRepo, defectPath): 

"""Ingest defect images. 

 

Parameters 

---------- 

repo : `str` 

The output repository location on disk for raw images. Must exist. 

calibRepo : `str` 

The output repository location on disk for calibration files. Must 

exist. 

defectPath : `str` 

Path to the defects in standard text form. This is probably a path in ``obs_decam_data``. 

 

Raises 

------ 

RuntimeError 

Raised if ``defectTarball`` exists but is empty. 

""" 

 

defectargs = [repo, defectPath, "--calib", calibRepo] 

try: 

_runIngestTask(self.defectIngester, defectargs) 

except sqlite3.IntegrityError as detail: 

raise RuntimeError("Not all defect files are unique") from detail 

 

def _ingestRefcats(self, dataset, workspace): 

"""Ingest the refcats for use by LSST. 

 

After this method returns, the data repository in ``workspace`` shall 

contain all reference catalogs from ``dataset``. Operations on the 

repository shall not be able to modify ``dataset``. 

 

Parameters 

---------- 

dataset : `lsst.ap.verify.dataset.Dataset` 

The dataset on which the pipeline will be run. 

workspace : `lsst.ap.verify.workspace.Workspace` 

The location containing all ingestion repositories. 

 

Notes 

----- 

Refcats are not, at present, registered as part of the repository. They 

are not guaranteed to be visible to anything other than a 

``refObjLoader``. See the [refcat Community thread](https://community.lsst.org/t/1523) 

for more details. 

""" 

if os.path.exists(os.path.join(workspace.dataRepo, "ref_cats")): 

self.log.info("Refcats were previously ingested, skipping...") 

else: 

self.log.info("Ingesting reference catalogs...") 

self._doIngestRefcats(workspace.dataRepo, dataset.refcatsLocation) 

self.log.info("Reference catalogs are now ingested in {0}".format(workspace.dataRepo)) 

 

def _doIngestRefcats(self, repo, refcats): 

"""Place refcats inside a particular repository. 

 

Parameters 

---------- 

repo : `str` 

The output repository location on disk for raw images. Must exist. 

refcats : `str` 

A directory containing .tar.gz files with LSST-formatted astrometric 

or photometric reference catalog information. 

""" 

for refcatName, tarball in self.config.refcats.items(): 

tarball = os.path.join(refcats, tarball) 

refcatDir = os.path.join(repo, "ref_cats", refcatName) 

with tarfile.open(tarball, "r") as opened: 

opened.extractall(refcatDir) 

 

def _copyConfigs(self, dataset, workspace): 

"""Give a workspace a copy of all configs associated with the ingested data. 

 

After this method returns, the config directory in ``workspace`` shall 

contain all config files from ``dataset``. 

 

Parameters 

---------- 

dataset : `lsst.ap.verify.dataset.Dataset` 

The dataset on which the pipeline will be run. 

workspace : `lsst.ap.verify.workspace.Workspace` 

The location containing the config directory. 

""" 

if os.listdir(workspace.configDir): 

self.log.info("Configs already copied, skipping...") 

else: 

self.log.info("Storing data-specific configs...") 

self._doCopyConfigs(workspace.configDir, dataset.configLocation) 

self.log.info("Configs are now stored in {0}".format(workspace.configDir)) 

 

def _doCopyConfigs(self, destination, source): 

"""Place configs inside a particular repository. 

 

Parameters 

---------- 

destination : `str` 

The directory to which the configs must be copied. Must exist. 

source : `str` 

A directory containing Task config files. 

""" 

for configFile in _findMatchingFiles(source, ['*.py']): 

shutil.copy2(configFile, destination) 

 

 

def ingestDataset(dataset, workspace): 

"""Ingest the contents of a dataset into a Butler repository. 

 

The original data directory shall not be modified. 

 

Parameters 

---------- 

dataset : `lsst.ap.verify.dataset.Dataset` 

The dataset to be ingested. 

workspace : `lsst.ap.verify.workspace.Workspace` 

The abstract location where ingestion repositories will be created. 

If the repositories already exist, they must be compatible with 

``dataset`` (in particular, they must support the relevant 

``obs`` package). 

""" 

# TODO: generalize to support arbitrary URIs (DM-11482) 

log = lsst.log.Log.getLogger("ap.verify.ingestion.ingestDataset") 

 

ingester = DatasetIngestTask(config=_getConfig(dataset)) 

ingester.run(dataset, workspace) 

log.info("Data ingested") 

 

 

def _getConfig(dataset): 

"""Return the ingestion config associated with a specific dataset. 

 

Parameters 

---------- 

dataset : `lsst.ap.verify.dataset.Dataset` 

The dataset whose ingestion config is desired. 

 

Returns 

------- 

config : `DatasetIngestConfig` 

The config for running `DatasetIngestTask` on ``dataset``. 

""" 

overrideFile = DatasetIngestTask._DefaultName + ".py" 

packageDir = lsst.utils.getPackageDir(dataset.obsPackage) 

 

config = DatasetIngestTask.ConfigClass() 

for path in [ 

os.path.join(packageDir, 'config'), 

os.path.join(packageDir, 'config', dataset.camera), 

dataset.configLocation, 

]: 

overridePath = os.path.join(path, overrideFile) 

if os.path.exists(overridePath): 

config.load(overridePath) 

return config 

 

 

def _runIngestTask(task, args): 

"""Run an ingestion task on a set of inputs. 

 

Parameters 

---------- 

task : `lsst.pipe.tasks.IngestTask` 

The task to run. 

args : list of command-line arguments, split using Python conventions 

The command-line arguments for ``task``. Must be compatible with ``task.ArgumentParser``. 

""" 

argumentParser = task.ArgumentParser(name=task.getName()) 

try: 

parsedCmd = argumentParser.parse_args(config=task.config, args=args) 

except SystemExit as e: 

# SystemExit is not an appropriate response when the arguments aren't user-supplied 

raise ValueError("Invalid ingestion arguments: %s" % args) from e 

task.run(parsedCmd) 

 

 

def _findMatchingFiles(basePath, include, exclude=None): 

"""Recursively identify files matching one set of patterns and not matching another. 

 

Parameters 

---------- 

basePath : `str` 

The path on disk where the files in ``include`` are located. 

include : iterable of `str` 

A collection of files (with wildcards) to include. Must not 

contain paths. 

exclude : iterable of `str`, optional 

A collection of filenames (with wildcards) to exclude. Must not 

contain paths. If omitted, all files matching ``include`` are returned. 

 

Returns 

------- 

files : `set` of `str` 

The files in ``basePath`` or any subdirectory that match ``include`` 

but not ``exclude``. 

""" 

_exclude = exclude if exclude is not None else [] 

 

allFiles = set() 

for pattern in include: 

allFiles.update(glob(os.path.join(basePath, '**', pattern), recursive=True)) 

 

for pattern in _exclude: 

allFiles.difference_update(fnmatch.filter(allFiles, pattern)) 

return allFiles 

 

 

@contextmanager 

def _tempChDir(newDir): 

"""Change to a new directory, while avoiding side effects in external code. 

 

Note that no side effects are guaranteed in the case of normal operation or 

for exceptions raised by the body of a ``with`` statement, but not for 

exceptions raised by ``_tempChDir`` itself (see below). 

 

This context manager cannot be used with "with ... as" statements. 

 

Parameters 

---------- 

newDir : `str` 

The directory to change to for the duration of a ``with`` statement. 

 

Raises 

------ 

OSError 

Raised if either the program cannot change to ``newDir``, or if it 

cannot undo the change. Failing to change to ``newDir`` is 

exception-safe (no side effects), but failing to undo is 

not recoverable. 

""" 

startDir = os.path.abspath(os.getcwd()) 

os.chdir(newDir) 

try: 

yield 

finally: 

os.chdir(startDir)