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

# 

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

# 

import os 

import numpy as np 

 

import lsst.daf.base as dafBase 

import lsst.pex.config as pexConfig 

import lsst.afw.geom as afwGeom 

import lsst.afw.geom.ellipses as afwEll 

import lsst.afw.display.ds9 as ds9 

import lsst.afw.image as afwImage 

import lsst.afw.math as afwMath 

import lsst.meas.algorithms as measAlg 

import lsst.meas.algorithms.utils as maUtils 

import lsst.meas.extensions.psfex as psfex 

 

 

class PsfexPsfDeterminerConfig(measAlg.BasePsfDeterminerConfig): 

__nEigenComponents = pexConfig.Field( 

doc="number of eigen components for PSF kernel creation", 

dtype=int, 

default=4, 

) 

spatialOrder = pexConfig.Field( 

doc="specify spatial order for PSF kernel creation", 

dtype=int, 

default=2, 

check=lambda x: x >= 0, 

) 

sizeCellX = pexConfig.Field( 

doc="size of cell used to determine PSF (pixels, column direction)", 

dtype=int, 

default=256, 

# minValue = 10, 

check=lambda x: x >= 10, 

) 

sizeCellY = pexConfig.Field( 

doc="size of cell used to determine PSF (pixels, row direction)", 

dtype=int, 

default=sizeCellX.default, 

# minValue = 10, 

check=lambda x: x >= 10, 

) 

__nStarPerCell = pexConfig.Field( 

doc="number of stars per psf cell for PSF kernel creation", 

dtype=int, 

default=3, 

) 

samplingSize = pexConfig.Field( 

doc="Resolution of the internal PSF model relative to the pixel size; " 

"e.g. 0.5 is equal to 2x oversampling", 

dtype=float, 

default=1, 

) 

badMaskBits = pexConfig.ListField( 

doc="List of mask bits which cause a source to be rejected as bad " 

"N.b. INTRP is used specially in PsfCandidateSet; it means \"Contaminated by neighbour\"", 

dtype=str, 

default=["INTRP", "SAT"], 

) 

psfexBasis = pexConfig.ChoiceField( 

doc="BASIS value given to psfex. PIXEL_AUTO will use the requested samplingSize only if " 

"the FWHM < 3 pixels. Otherwise, it will use samplingSize=1. PIXEL will always use the " 

"requested samplingSize", 

dtype=str, 

allowed={ 

"PIXEL": "Always use requested samplingSize", 

"PIXEL_AUTO": "Only use requested samplingSize when FWHM < 3", 

}, 

default='PIXEL', 

optional=False, 

) 

__borderWidth = pexConfig.Field( 

doc="Number of pixels to ignore around the edge of PSF candidate postage stamps", 

dtype=int, 

default=0, 

) 

__nStarPerCellSpatialFit = pexConfig.Field( 

doc="number of stars per psf Cell for spatial fitting", 

dtype=int, 

default=5, 

) 

__constantWeight = pexConfig.Field( 

doc="Should each PSF candidate be given the same weight, independent of magnitude?", 

dtype=bool, 

default=True, 

) 

__nIterForPsf = pexConfig.Field( 

doc="number of iterations of PSF candidate star list", 

dtype=int, 

default=3, 

) 

tolerance = pexConfig.Field( 

doc="tolerance of spatial fitting", 

dtype=float, 

default=1e-2, 

) 

lam = pexConfig.Field( 

doc="floor for variance is lam*data", 

dtype=float, 

default=0.05, 

) 

reducedChi2ForPsfCandidates = pexConfig.Field( 

doc="for psf candidate evaluation", 

dtype=float, 

default=2.0, 

) 

spatialReject = pexConfig.Field( 

doc="Rejection threshold (stdev) for candidates based on spatial fit", 

dtype=float, 

default=3.0, 

) 

recentroid = pexConfig.Field( 

doc="Should PSFEX be permitted to recentroid PSF candidates?", 

dtype=bool, 

default=False, 

) 

 

def setDefaults(self): 

self.kernelSize = 41 

 

 

class PsfexPsfDeterminerTask(measAlg.BasePsfDeterminerTask): 

ConfigClass = PsfexPsfDeterminerConfig 

 

def determinePsf(self, exposure, psfCandidateList, metadata=None, flagKey=None): 

"""Determine a PSFEX PSF model for an exposure given a list of PSF candidates 

 

@param[in] exposure: exposure containing the psf candidates (lsst.afw.image.Exposure) 

@param[in] psfCandidateList: a sequence of PSF candidates (each an lsst.meas.algorithms.PsfCandidate); 

typically obtained by detecting sources and then running them through a star selector 

@param[in,out] metadata a home for interesting tidbits of information 

@param[in] flagKey: schema key used to mark sources actually used in PSF determination 

 

@return psf: a meas.extensions.psfex.PsfexPsf 

""" 

import lsstDebug 

display = lsstDebug.Info(__name__).display 

displayExposure = display and \ 

lsstDebug.Info(__name__).displayExposure # display the Exposure + spatialCells 

displayPsfComponents = display and \ 

lsstDebug.Info(__name__).displayPsfComponents # show the basis functions 

showBadCandidates = display and \ 

lsstDebug.Info(__name__).showBadCandidates # Include bad candidates (meaningless, methinks) 

displayResiduals = display and \ 

lsstDebug.Info(__name__).displayResiduals # show residuals 

displayPsfMosaic = display and \ 

lsstDebug.Info(__name__).displayPsfMosaic # show mosaic of reconstructed PSF(x,y) 

normalizeResiduals = lsstDebug.Info(__name__).normalizeResiduals 

# Normalise residuals by object amplitude 

 

mi = exposure.getMaskedImage() 

 

nCand = len(psfCandidateList) 

174 ↛ 175line 174 didn't jump to line 175, because the condition on line 174 was never true if nCand == 0: 

raise RuntimeError("No PSF candidates supplied.") 

# 

# How big should our PSF models be? 

# 

179 ↛ 181line 179 didn't jump to line 181, because the condition on line 179 was never true if display: # only needed for debug plots 

# construct and populate a spatial cell set 

bbox = mi.getBBox(afwImage.PARENT) 

psfCellSet = afwMath.SpatialCellSet(bbox, self.config.sizeCellX, self.config.sizeCellY) 

else: 

psfCellSet = None 

 

sizes = np.empty(nCand) 

for i, psfCandidate in enumerate(psfCandidateList): 

try: 

189 ↛ 190line 189 didn't jump to line 190, because the condition on line 189 was never true if psfCellSet: 

psfCellSet.insertCandidate(psfCandidate) 

except Exception as e: 

self.log.debug("Skipping PSF candidate %d of %d: %s", i, len(psfCandidateList), e) 

continue 

 

source = psfCandidate.getSource() 

quad = afwEll.Quadrupole(source.getIxx(), source.getIyy(), source.getIxy()) 

rmsSize = quad.getTraceRadius() 

sizes[i] = rmsSize 

 

200 ↛ 204line 200 didn't jump to line 204, because the condition on line 200 was never false if self.config.kernelSize >= 15: 

self.log.warn("NOT scaling kernelSize by stellar quadrupole moment, but using absolute value") 

actualKernelSize = int(self.config.kernelSize) 

else: 

actualKernelSize = 2 * int(self.config.kernelSize * np.sqrt(np.median(sizes)) + 0.5) + 1 

if actualKernelSize < self.config.kernelSizeMin: 

actualKernelSize = self.config.kernelSizeMin 

if actualKernelSize > self.config.kernelSizeMax: 

actualKernelSize = self.config.kernelSizeMax 

if display: 

rms = np.median(sizes) 

print("Median PSF RMS size=%.2f pixels (\"FWHM\"=%.2f)" % (rms, 2*np.sqrt(2*np.log(2))*rms)) 

 

# If we manually set the resolution then we need the size in pixel units 

pixKernelSize = actualKernelSize 

215 ↛ 219line 215 didn't jump to line 219, because the condition on line 215 was never false if self.config.samplingSize > 0: 

pixKernelSize = int(actualKernelSize*self.config.samplingSize) 

217 ↛ 218line 217 didn't jump to line 218, because the condition on line 217 was never true if pixKernelSize % 2 == 0: 

pixKernelSize += 1 

self.log.trace("Psfex Kernel size=%.2f, Image Kernel Size=%.2f", actualKernelSize, pixKernelSize) 

psfCandidateList[0].setHeight(pixKernelSize) 

psfCandidateList[0].setWidth(pixKernelSize) 

 

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- BEGIN PSFEX 

# 

# Insert the good candidates into the set 

# 

defaultsFile = os.path.join(os.environ["MEAS_EXTENSIONS_PSFEX_DIR"], "config", "default-lsst.psfex") 

args_md = dafBase.PropertySet() 

args_md.set("BASIS_TYPE", str(self.config.psfexBasis)) 

args_md.set("PSFVAR_DEGREES", str(self.config.spatialOrder)) 

args_md.set("PSF_SIZE", str(actualKernelSize)) 

args_md.set("PSF_SAMPLING", str(self.config.samplingSize)) 

prefs = psfex.Prefs(defaultsFile, args_md) 

prefs.setCommandLine([]) 

prefs.addCatalog("psfexPsfDeterminer") 

 

prefs.use() 

principalComponentExclusionFlag = bool(bool(psfex.Context.REMOVEHIDDEN) 

if False else psfex.Context.KEEPHIDDEN) 

context = psfex.Context(prefs.getContextName(), prefs.getContextGroup(), 

prefs.getGroupDeg(), principalComponentExclusionFlag) 

set = psfex.Set(context) 

set.setVigSize(pixKernelSize, pixKernelSize) 

set.setFwhm(2*np.sqrt(2*np.log(2))*np.median(sizes)) 

set.setRecentroid(self.config.recentroid) 

 

catindex, ext = 0, 0 

backnoise2 = afwMath.makeStatistics(mi.getImage(), afwMath.VARIANCECLIP).getValue() 

ccd = exposure.getDetector() 

250 ↛ 251line 250 didn't jump to line 251, because the condition on line 250 was never true if ccd: 

gain = np.mean(np.array([a.getGain() for a in ccd])) 

else: 

gain = 1.0 

self.log.warn("Setting gain to %g" % (gain,)) 

 

contextvalp = [] 

for i, key in enumerate(context.getName()): 

258 ↛ 259line 258 didn't jump to line 259, because the condition on line 258 was never true if context.getPcflag(i): 

contextvalp.append(pcval[pc]) 

pc += 1 

261 ↛ 262line 261 didn't jump to line 262, because the condition on line 261 was never true elif key[0] == ':': 

try: 

contextvalp.append(exposure.getMetadata().getScalar(key[1:])) 

except KeyError: 

raise RuntimeError("*Error*: %s parameter not found in the header of %s" % 

(key[1:], prefs.getContextName())) 

else: 

try: 

contextvalp.append(np.array([psfCandidateList[_].getSource().get(key) 

for _ in range(nCand)])) 

except KeyError: 

raise RuntimeError("*Error*: %s parameter not found" % (key,)) 

set.setContextname(i, key) 

 

275 ↛ 276line 275 didn't jump to line 276, because the condition on line 275 was never true if display: 

frame = 0 

if displayExposure: 

ds9.mtv(exposure, frame=frame, title="psf determination") 

 

badBits = mi.getMask().getPlaneBitMask(self.config.badMaskBits) 

fluxName = prefs.getPhotfluxRkey() 

fluxFlagName = "base_" + fluxName + "_flag" 

 

xpos, ypos = [], [] 

for i, psfCandidate in enumerate(psfCandidateList): 

source = psfCandidate.getSource() 

xc, yc = source.getX(), source.getY() 

try: 

int(xc), int(yc) 

except ValueError: 

continue 

 

try: 

pstamp = psfCandidate.getMaskedImage().clone() 

except Exception as e: 

continue 

 

298 ↛ 299line 298 didn't jump to line 299, because the condition on line 298 was never true if fluxFlagName in source.schema and source.get(fluxFlagName): 

continue 

 

flux = source.get(fluxName) 

302 ↛ 303line 302 didn't jump to line 303, because the condition on line 302 was never true if flux < 0 or np.isnan(flux): 

continue 

 

# From this point, we're configuring the "sample" (PSFEx's version of a PSF candidate). 

# Having created the sample, we must proceed to configure it, and then fini (finalize), 

# or it will be malformed. 

try: 

sample = set.newSample() 

sample.setCatindex(catindex) 

sample.setExtindex(ext) 

sample.setObjindex(i) 

 

imArray = pstamp.getImage().getArray() 

imArray[np.where(np.bitwise_and(pstamp.getMask().getArray(), badBits))] = \ 

-2*psfex.BIG 

sample.setVig(imArray) 

 

sample.setNorm(flux) 

sample.setBacknoise2(backnoise2) 

sample.setGain(gain) 

sample.setX(xc) 

sample.setY(yc) 

sample.setFluxrad(sizes[i]) 

 

for j in range(set.getNcontext()): 

sample.setContext(j, float(contextvalp[j][i])) 

except Exception as e: 

self.log.debug("Exception when processing sample at (%f,%f): %s", xc, yc, e) 

continue 

else: 

set.finiSample(sample) 

 

xpos.append(xc) # for QA 

ypos.append(yc) 

 

337 ↛ 338line 337 didn't jump to line 338, because the condition on line 337 was never true if displayExposure: 

with ds9.Buffering(): 

ds9.dot("o", xc, yc, ctype=ds9.CYAN, size=4, frame=frame) 

 

341 ↛ 342line 341 didn't jump to line 342, because the condition on line 341 was never true if set.getNsample() == 0: 

raise RuntimeError("No good PSF candidates to pass to PSFEx") 

 

#---- Update min and max and then the scaling 

for i in range(set.getNcontext()): 

cmin = contextvalp[i].min() 

cmax = contextvalp[i].max() 

set.setContextScale(i, cmax - cmin) 

set.setContextOffset(i, (cmin + cmax)/2.0) 

 

# Don't waste memory! 

set.trimMemory() 

 

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- END PSFEX 

# 

# Do a PSFEX decomposition of those PSF candidates 

# 

fields = [] 

field = psfex.Field("Unknown") 

field.addExt(exposure.getWcs(), exposure.getWidth(), exposure.getHeight(), set.getNsample()) 

field.finalize() 

 

fields.append(field) 

 

sets = [] 

sets.append(set) 

 

psfex.makeit(fields, sets) 

psfs = field.getPsfs() 

 

# Flag which objects were actually used in psfex by 

good_indices = [] 

for i in range(sets[0].getNsample()): 

index = sets[0].getSample(i).getObjindex() 

375 ↛ 373line 375 didn't jump to line 373, because the condition on line 375 was never false if index > -1: 

good_indices.append(index) 

 

378 ↛ 379line 378 didn't jump to line 379, because the condition on line 378 was never true if flagKey is not None: 

for i, psfCandidate in enumerate(psfCandidateList): 

source = psfCandidate.getSource() 

if i in good_indices: 

source.set(flagKey, True) 

 

xpos = np.array(xpos) 

ypos = np.array(ypos) 

numGoodStars = len(good_indices) 

avgX, avgY = np.mean(xpos), np.mean(ypos) 

 

psf = psfex.PsfexPsf(psfs[0], afwGeom.Point2D(avgX, avgY)) 

 

391 ↛ 392line 391 didn't jump to line 392, because the condition on line 391 was never true if False and (displayResiduals or displayPsfMosaic): 

ext = 0 

frame = 1 

diagnostics = True 

catDir = "." 

title = "psfexPsfDeterminer" 

psfex.psfex.showPsf(psfs, set, ext, 

[(exposure.getWcs(), exposure.getWidth(), exposure.getHeight())], 

nspot=3, trim=5, frame=frame, diagnostics=diagnostics, outDir=catDir, 

title=title) 

# 

# Display code for debugging 

# 

404 ↛ 405line 404 didn't jump to line 405, because the condition on line 404 was never true if display: 

assert psfCellSet is not None 

 

if displayExposure: 

maUtils.showPsfSpatialCells(exposure, psfCellSet, showChi2=True, 

symb="o", ctype=ds9.YELLOW, ctypeBad=ds9.RED, size=8, frame=frame) 

if displayResiduals: 

maUtils.showPsfCandidates(exposure, psfCellSet, psf=psf, frame=4, 

normalize=normalizeResiduals, 

showBadCandidates=showBadCandidates) 

if displayPsfComponents: 

maUtils.showPsf(psf, frame=6) 

if displayPsfMosaic: 

maUtils.showPsfMosaic(exposure, psf, frame=7, showFwhm=True) 

ds9.scale('linear', 0, 1, frame=7) 

# 

# Generate some QA information 

# 

# Count PSF stars 

# 

424 ↛ 431line 424 didn't jump to line 431, because the condition on line 424 was never false if metadata is not None: 

metadata.set("spatialFitChi2", np.nan) 

metadata.set("numAvailStars", nCand) 

metadata.set("numGoodStars", numGoodStars) 

metadata.set("avgX", avgX) 

metadata.set("avgY", avgY) 

 

psfCellSet = None 

return psf, psfCellSet 

 

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 

 

measAlg.psfDeterminerRegistry.register("psfex", PsfexPsfDeterminerTask)