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

# This file is part of meas_base. 

# 

# Developed for the LSST Data Management System. 

# This product includes software developed by the LSST Project 

# (https://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 <https://www.gnu.org/licenses/>. 

 

""" 

Subtasks for creating the reference catalogs used in forced measurement. 

""" 

 

import lsst.geom 

import lsst.pex.config 

import lsst.pipe.base 

 

__all__ = ("BaseReferencesTask", "CoaddSrcReferencesTask") 

 

 

class BaseReferencesConfig(lsst.pex.config.Config): 

"""Default configuration for reference source selection. 

""" 

 

removePatchOverlaps = lsst.pex.config.Field( 

doc="Only include reference sources for each patch that lie within the patch's inner bbox", 

dtype=bool, 

default=True 

) 

filter = lsst.pex.config.Field( 

doc="Bandpass for reference sources; None indicates chi-squared detections.", 

dtype=str, 

optional=True 

) 

 

 

class BaseReferencesTask(lsst.pipe.base.Task): 

"""Base class for forced photometry subtask that fetches reference sources. 

 

Parameters 

---------- 

schema : `lsst.afw.table.Schema`, optional 

The schema of the reference catalog. 

butler : `lsst.daf.persistence.butler.Butler`, optional 

A butler that will allow the task to load its schema from disk. 

 

Notes 

----- 

At least one of the ``schema`` and ``butler`` arguments must be present; 

if both are, ``schema`` takes precedence. 

 

``BaseReferencesTask`` defines the required API for the references task, 

which consists of: 

 

- ``getSchema(butler)`` 

- ``fetchInPatches(butler, tract, filter, patchList)`` 

- ``fetchInBox(self, butler, tract, filter, bbox, wcs)`` 

- the ``removePatchOverlaps`` config option 

 

It also provides the ``subset`` method, which may be of use to derived 

classes when reimplementing ``fetchInBox``. 

""" 

 

ConfigClass = BaseReferencesConfig 

"""Configuration class associated with this task (`lsst.pex.config.Config`). 

""" 

 

def __init__(self, butler=None, schema=None, **kwargs): 

lsst.pipe.base.Task.__init__(self, **kwargs) 

 

def getSchema(self, butler): 

"""Return the schema for the reference sources. 

 

Parameters 

---------- 

butler : `lsst.daf.persistence.butler.Butler` 

Data butler from which the schema will be fetched. 

 

Notes 

----- 

Must be available even before any data has been processed. 

""" 

raise NotImplementedError("BaseReferencesTask is pure abstract, and cannot be used directly.") 

 

def getWcs(self, dataRef): 

"""Return the WCS for reference sources. 

 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.ButlerDataRef` 

The data reference from which the WCS will be fetched. This must 

include the tract in its dataId. 

""" 

raise NotImplementedError("BaseReferencesTask is pure abstract, and cannot be used directly.") 

 

def fetchInBox(self, dataRef, bbox, wcs): 

"""Return reference sources within a given bounding box. 

 

Reference sources are selected if they overlap a region defined by a 

pixel-coordinate bounding box and corresponding WCS. 

 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.ButlerDataRef` 

Butler data reference. The implied data ID must contain the 

``tract`` key. 

bbox : `lsst.afw.geom.Box2I` or `lsst.afw.geom.Box2D` 

Defines the selection region in pixel coordinates. 

wcs : `lsst.afw.image.SkyWcs` 

Maps ``bbox`` to sky coordinates. 

 

Returns 

------- 

sources : iterable of `~lsst.afw.table.SourceRecord` 

Reference sources. May be any Python iterable, including a lazy 

iterator. 

 

Notes 

----- 

The returned set of sources should be complete and close to minimal. 

""" 

raise NotImplementedError("BaseReferencesTask is pure abstract, and cannot be used directly.") 

 

def fetchInPatches(self, dataRef, patchList): 

"""Return reference sources within one or more patches. 

 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.ButlerDataRef` 

Butler data reference. The implied data ID must contain the 

``tract`` key. 

patchList : `list` of `lsst.skymap.PatchInfo` 

Patches for which to fetch reference sources. 

 

Returns 

------- 

sources : iterable of `~lsst.afw.table.SourceRecord` 

Reference sources. May be any Python iterable, including a lazy 

iterator. 

 

Notes 

----- 

The returned set of sources should be complete and close to minimal. 

 

If ``config.removePatchOverlaps`` is `True`, only sources within each 

patch's "inner" bounding box should be returned. 

""" 

raise NotImplementedError("BaseReferencesTask is pure abstract, and cannot be used directly.") 

 

def subset(self, sources, bbox, wcs): 

"""Filter a list of sources to only those within the bounding box. 

 

Parameters 

---------- 

sources : iterable of `~lsst.afw.table.SourceRecord` 

Reference sources. May be any Python iterable, including a lazy 

iterator. 

bbox : `lsst.afw.geom.Box2I` or `lsst.afw.geom.Box2D` 

Defines the selection region. 

wcs : `lsst.afw.image.SkyWcs` 

Maps ``bbox`` to sky coordinates. 

 

Returns 

------- 

sources : iterable of `~lsst.afw.table.SourceRecord` 

Filtered sources. May be any Python iterable, including a lazy 

iterator. 

 

Notes 

----- 

Instead of filtering sources directly via their positions, we filter 

based on the positions of parent objects, then include or discard all 

children based on their parent's status. This is necessary to support 

replacement with noise in measurement, which requires all child 

sources have their parent present. 

 

This is not a part of the required `BaseReferencesTask` interface; 

it's a convenience function used in implementing `fetchInBox` that may 

be of use to subclasses. 

""" 

boxD = lsst.geom.Box2D(bbox) 

# We're passed an arbitrary iterable, but we need a catalog so we can 

# iterate over parents and then children. 

catalog = lsst.afw.table.SourceCatalog(self.schema) 

catalog.extend(sources) 

# catalog must be sorted by parent ID for lsst.afw.table.getChildren 

# to work 

catalog.sort(lsst.afw.table.SourceTable.getParentKey()) 

# Iterate over objects that have no parent. 

parentSources = catalog.getChildren(0) 

skyCoordList = [source.getCoord() for source in parentSources] 

pixelPosList = wcs.skyToPixel(skyCoordList) 

for parent, pixel in zip(parentSources, pixelPosList): 

if boxD.contains(pixel): 

yield parent 

for child in catalog.getChildren(parent.getId()): 

yield child 

 

 

class CoaddSrcReferencesConfig(BaseReferencesTask.ConfigClass): 

"""Default configuration for coadd reference source selection. 

""" 

 

coaddName = lsst.pex.config.Field( 

doc="Coadd name: typically one of deep or goodSeeing.", 

dtype=str, 

default="deep", 

) 

skipMissing = lsst.pex.config.Field( 

doc="Silently skip patches where the reference catalog does not exist.", 

dtype=bool, 

default=False 

) 

 

def validate(self): 

if (self.coaddName == "chiSquared") != (self.filter is None): 

raise lsst.pex.config.FieldValidationError( 

field=CoaddSrcReferencesConfig.coaddName, 

config=self, 

msg="filter may be None if and only if coaddName is chiSquared" 

) 

 

 

class CoaddSrcReferencesTask(BaseReferencesTask): 

"""Select reference sources by loading the “coadd source” dataset directly. 

 

The name of the dataset to read is generated by appending the 

`datasetSuffix` attribute to the string ``Coadd_``. The dataset is then 

read directly from disk using the Butler. 

 

Parameters 

---------- 

schema : `lsst.afw.table.Schema`, optional 

The schema of the detection catalogs used as input to this one. 

butler : `lsst.daf.persistence.butler.Butler`, optional 

A Butler used to read the input schema from disk. Required if 

``schema`` is `None`. 

 

Notes 

----- 

The task will set its own ``self.schema`` attribute to the schema of the 

output merged catalog. 

""" 

 

ConfigClass = CoaddSrcReferencesConfig 

"""Configuration class associated with this task (`lsst.pex.config.Config`). 

""" 

 

datasetSuffix = "src" 

"""Suffix to append to ``Coadd_`` to generate the dataset name (`str`). 

""" 

 

def __init__(self, butler=None, schema=None, **kwargs): 

BaseReferencesTask.__init__(self, butler=butler, schema=schema, **kwargs) 

if schema is None: 

assert butler is not None, "No butler nor schema provided" 

schema = butler.get("{}Coadd_{}_schema".format(self.config.coaddName, self.datasetSuffix), 

immediate=True).getSchema() 

self.schema = schema 

 

def getWcs(self, dataRef): 

"""Return the WCS for reference sources. 

 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.ButlerDataRef` 

Butler data reference. Must includ the trac in its dataId. 

""" 

skyMap = dataRef.get(self.config.coaddName + "Coadd_skyMap", immediate=True) 

return skyMap[dataRef.dataId["tract"]].getWcs() 

 

def fetchInPatches(self, dataRef, patchList): 

"""Fetch the source catalog using the Butler. 

 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.ButlerDataRef` 

Butler data reference. The implied data ID must contain the 

``tract`` key. 

patchList : `list` of `lsst.skymap.PatchInfo` 

Patches for which to fetch reference sources. 

 

Returns 

------- 

sources : iterable of `~lsst.afw.table.SourceRecord` 

Reference sources. May be any Python iterable, including a lazy 

iterator. 

 

Notes 

----- 

An implementation of `BaseReferencesTask.fetchInPatches` that loads 

``Coadd_`` + `datasetSuffix` catalogs using the butler. 

""" 

dataset = "{}Coadd_{}".format(self.config.coaddName, self.datasetSuffix) 

tract = dataRef.dataId["tract"] 

butler = dataRef.butlerSubset.butler 

for patch in patchList: 

dataId = {'tract': tract, 'patch': "%d,%d" % patch.getIndex()} 

if self.config.filter is not None: 

dataId['filter'] = self.config.filter 

 

if not butler.datasetExists(dataset, dataId): 

if self.config.skipMissing: 

continue 

raise lsst.pipe.base.TaskError("Reference %s doesn't exist" % (dataId,)) 

self.log.info("Getting references in %s" % (dataId,)) 

catalog = butler.get(dataset, dataId, immediate=True) 

if self.config.removePatchOverlaps: 

bbox = lsst.geom.Box2D(patch.getInnerBBox()) 

for source in catalog: 

if bbox.contains(source.getCentroid()): 

yield source 

else: 

for source in catalog: 

yield source 

 

def fetchInBox(self, dataRef, bbox, wcs, pad=0): 

"""Return reference sources within a given bounding box. 

 

Reference sources are selected if they overlap a region defined by a 

pixel-coordinate bounding box and corresponding WCS. 

 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.ButlerDataRef` 

Butler data reference. The implied data ID must contain the 

``tract`` key. 

bbox : `lsst.afw.geom.Box2I` or `lsst.afw.geom.Box2D` 

Defines the selection region in pixel coordinates. 

wcs : `lsst.afw.image.SkyWcs` 

Maps ``bbox`` to sky coordinates. 

pad : `int` 

a buffer to grow the bounding box by after catalogs have been loaded, but 

before filtering them to include just the given bounding box. 

 

Returns 

------- 

sources : iterable of `~lsst.afw.table.SourceRecord` 

Reference sources. May be any Python iterable, including a lazy 

iterator. 

""" 

skyMap = dataRef.get(self.config.coaddName + "Coadd_skyMap", immediate=True) 

tract = skyMap[dataRef.dataId["tract"]] 

coordList = [wcs.pixelToSky(corner) for corner in lsst.geom.Box2D(bbox).getCorners()] 

self.log.info("Getting references in region with corners %s [degrees]" % 

", ".join("(%s)" % (coord.getPosition(lsst.geom.degrees),) for coord in coordList)) 

patchList = tract.findPatchList(coordList) 

# After figuring out which patch catalogs to read from the bbox, pad out the bbox if desired 

# But don't add any new patches while padding 

if pad: 

bbox.grow(pad) 

return self.subset(self.fetchInPatches(dataRef, patchList), bbox, wcs) 

 

 

class MultiBandReferencesConfig(CoaddSrcReferencesTask.ConfigClass): 

"""Default configuration for multi-band reference source selection. 

""" 

 

def validate(self): 

if self.filter is not None: 

raise lsst.pex.config.FieldValidationError( 

field=MultiBandReferencesConfig.filter, 

config=self, 

msg="Filter should not be set for the multiband processing scheme") 

# Delegate to ultimate base class, because the direct one has a check we don't want. 

BaseReferencesTask.ConfigClass.validate(self) 

 

 

class MultiBandReferencesTask(CoaddSrcReferencesTask): 

"""Loads references from the multi-band processing scheme. 

""" 

 

ConfigClass = MultiBandReferencesConfig 

datasetSuffix = "ref" # Documented in superclass