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

#!/usr/bin/env python 

# 

# LSST Data Management System 

# Copyright 2008-2015 AURA/LSST. 

# 

# This product includes software developed by the 

# LSST Project (http://www.lsst.org/). 

# 

# 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 LSST License Statement and 

# the GNU General Public License along with this program. If not, 

# see <https://www.lsstcorp.org/LegalNotices/>. 

# 

""" 

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): 

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 retrieves reference sources. 

 

BaseReferencesTask defines the required API for the references task, which includes: 

- 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 

 

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

"""!Initialize the task. 

 

BaseReferencesTask and its subclasses take two keyword arguments beyond the usual Task arguments: 

- schema: the Schema of the reference catalog 

- butler: a butler that will allow the task to load its Schema from disk. 

At least one of these arguments must be present; if both are, schema takes precedence. 

""" 

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

 

def getSchema(self, butler): 

"""! 

Return the schema for the reference sources. 

 

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. The given dataRef 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 that overlap a region defined by a pixel-coordinate bounding box 

and corresponding Wcs. 

 

@param[in] dataRef ButlerDataRef; the implied data ID must contain the 'tract' key. 

@param[in] bbox a geom.Box2I or Box2D that defines the region in pixel coordinates 

@param[in] wcs afw.image.Wcs that maps the bbox to sky coordinates 

 

@return an iterable of reference sources 

 

It is not required that the returned object be a SourceCatalog; it may be any Python iterable 

containing SourceRecords (including a lazy iterator). 

 

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 that overlap a region defined by one or more SkyMap patches. 

 

@param[in] dataRef ButlerDataRef; the implied data ID must contain the 'tract' key. 

@param[in] patchList list of skymap.PatchInfo instances for which to fetch reference sources 

 

@return an iterable of reference sources 

 

It is not required that the returned object be a SourceCatalog; it may be any Python sequence 

containing SourceRecords (including a lazy iterator). 

 

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 sources to contain only those within the given box, defined in the coordinate system 

defined by the given Wcs. 

 

@param[in] sources input iterable of SourceRecords 

@param[in] bbox bounding box with which to filter reference sources (Box2I or Box2D) 

@param[in] wcs afw.image.Wcs that defines the coordinate system of bbox 

 

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 ReplaceWithNoise in measurement, which requires all child sources have 

their parent present. 

 

@return an iterable of filtered reference sources 

 

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): 

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): 

"""! 

A references task implementation that loads the coadd_datasetSuffix dataset directly from 

disk using the butler. 

""" 

 

ConfigClass = CoaddSrcReferencesConfig 

datasetSuffix = "src" # Suffix to add to "Coadd_" for dataset name 

 

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

"""! Initialize the task. 

Additional keyword arguments (forwarded to BaseReferencesTask.__init__): 

- schema: the schema of the detection catalogs used as input to this one 

- butler: a butler used to read the input schema from disk, if schema is None 

The task will set its own self.schema attribute to the schema of the output merged catalog. 

""" 

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. The given dataRef must include the tract in its dataId. 

""" 

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

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

 

def fetchInPatches(self, dataRef, patchList): 

"""! 

An implementation of BaseReferencesTask.fetchInPatches that loads 'coadd_' + datasetSuffix 

catalogs using the butler. 

 

The given dataRef must include the tract in its dataId. 

""" 

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 that overlap a region defined by a pixel-coordinate bounding box 

and corresponding Wcs. 

 

@param[in] dataRef ButlerDataRef; the implied data ID must contain the 'tract' key. 

@param[in] bbox a geom.Box2I or Box2D that defines the region in pixel coordinates 

@param[in] wcs afw.image.Wcs that maps the bbox to sky coordinates 

@param[in] pad a buffer to grow the bounding box by after catalogs have been loaded, but 

before filtering them to include just the given bounding box. 

 

@return an iterable of reference sources 

""" 

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): 

 

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 multiband processing scheme""" 

ConfigClass = MultiBandReferencesConfig 

datasetSuffix = "ref"