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

# 

# LSST Data Management System 

# 

# Copyright 2008-2017 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 sys 

 

import numpy 

import warnings 

from functools import reduce 

 

from lsst.log import Log 

from lsst.pipe.base import Struct 

import lsst.geom 

from lsst.afw.cameraGeom import PIXELS, TAN_PIXELS 

import lsst.afw.geom as afwGeom 

import lsst.pex.config as pexConfig 

import lsst.afw.display.ds9 as ds9 

from .sourceSelector import BaseSourceSelectorTask, sourceSelectorRegistry 

 

 

class ObjectSizeStarSelectorConfig(BaseSourceSelectorTask.ConfigClass): 

40 ↛ exitline 44 didn't finish the lambda on line 44 fluxMin = pexConfig.Field( 

doc="specify the minimum psfFlux for good Psf Candidates", 

dtype=float, 

default=12500.0, 

check=lambda x: x >= 0.0, 

) 

46 ↛ exitline 50 didn't finish the lambda on line 50 fluxMax = pexConfig.Field( 

doc="specify the maximum psfFlux for good Psf Candidates (ignored if == 0)", 

dtype=float, 

default=0.0, 

check=lambda x: x >= 0.0, 

) 

52 ↛ exitline 56 didn't finish the lambda on line 56 widthMin = pexConfig.Field( 

doc="minimum width to include in histogram", 

dtype=float, 

default=0.0, 

check=lambda x: x >= 0.0, 

) 

58 ↛ exitline 62 didn't finish the lambda on line 62 widthMax = pexConfig.Field( 

doc="maximum width to include in histogram", 

dtype=float, 

default=10.0, 

check=lambda x: x >= 0.0, 

) 

sourceFluxField = pexConfig.Field( 

doc="Name of field in Source to use for flux measurement", 

dtype=str, 

default="base_GaussianFlux_instFlux", 

) 

69 ↛ exitline 73 didn't finish the lambda on line 73 widthStdAllowed = pexConfig.Field( 

doc="Standard deviation of width allowed to be interpreted as good stars", 

dtype=float, 

default=0.15, 

check=lambda x: x >= 0.0, 

) 

75 ↛ exitline 79 didn't finish the lambda on line 79 nSigmaClip = pexConfig.Field( 

doc="Keep objects within this many sigma of cluster 0's median", 

dtype=float, 

default=2.0, 

check=lambda x: x >= 0.0, 

) 

badFlags = pexConfig.ListField( 

doc="List of flags which cause a source to be rejected as bad", 

dtype=str, 

default=[ 

"base_PixelFlags_flag_edge", 

"base_PixelFlags_flag_interpolatedCenter", 

"base_PixelFlags_flag_saturatedCenter", 

"base_PixelFlags_flag_crCenter", 

"base_PixelFlags_flag_bad", 

"base_PixelFlags_flag_interpolated", 

], 

) 

 

def validate(self): 

BaseSourceSelectorTask.ConfigClass.validate(self) 

if self.widthMin > self.widthMax: 

raise pexConfig.FieldValidationError("widthMin (%f) > widthMax (%f)" 

% (self.widthMin, self.widthMax)) 

 

 

class EventHandler: 

"""A class to handle key strokes with matplotlib displays""" 

 

def __init__(self, axes, xs, ys, x, y, frames=[0]): 

self.axes = axes 

self.xs = xs 

self.ys = ys 

self.x = x 

self.y = y 

self.frames = frames 

 

self.cid = self.axes.figure.canvas.mpl_connect('key_press_event', self) 

 

def __call__(self, ev): 

if ev.inaxes != self.axes: 

return 

 

if ev.key and ev.key in ("p"): 

dist = numpy.hypot(self.xs - ev.xdata, self.ys - ev.ydata) 

dist[numpy.where(numpy.isnan(dist))] = 1e30 

 

which = numpy.where(dist == min(dist)) 

 

x = self.x[which][0] 

y = self.y[which][0] 

for frame in self.frames: 

ds9.pan(x, y, frame=frame) 

ds9.cmdBuffer.flush() 

else: 

pass 

 

 

def _assignClusters(yvec, centers): 

"""Return a vector of centerIds based on their distance to the centers""" 

assert len(centers) > 0 

 

minDist = numpy.nan*numpy.ones_like(yvec) 

clusterId = numpy.empty_like(yvec) 

clusterId.dtype = int # zeros_like(..., dtype=int) isn't in numpy 1.5 

dbl = Log.getLogger("objectSizeStarSelector._assignClusters") 

dbl.setLevel(dbl.INFO) 

 

# Make sure we are logging aall numpy warnings... 

oldSettings = numpy.seterr(all="warn") 

with warnings.catch_warnings(record=True) as w: 

warnings.simplefilter("always") 

for i, mean in enumerate(centers): 

dist = abs(yvec - mean) 

if i == 0: 

update = dist == dist # True for all points 

else: 

update = dist < minDist 

if w: # Only do if w is not empty i.e. contains a warning message 

dbl.trace(str(w[-1])) 

 

minDist[update] = dist[update] 

clusterId[update] = i 

numpy.seterr(**oldSettings) 

 

return clusterId 

 

 

def _kcenters(yvec, nCluster, useMedian=False, widthStdAllowed=0.15): 

"""A classic k-means algorithm, clustering yvec into nCluster clusters 

 

Return the set of centres, and the cluster ID for each of the points 

 

If useMedian is true, use the median of the cluster as its centre, rather than 

the traditional mean 

 

Serge Monkewitz points out that there other (maybe smarter) ways of seeding the means: 

"e.g. why not use the Forgy or random partition initialization methods" 

however, the approach adopted here seems to work well for the particular sorts of things 

we're clustering in this application 

""" 

 

assert nCluster > 0 

 

mean0 = sorted(yvec)[len(yvec)//10] # guess 

delta = mean0 * widthStdAllowed * 2.0 

centers = mean0 + delta * numpy.arange(nCluster) 

 

func = numpy.median if useMedian else numpy.mean 

 

clusterId = numpy.zeros_like(yvec) - 1 # which cluster the points are assigned to 

clusterId.dtype = int # zeros_like(..., dtype=int) isn't in numpy 1.5 

while True: 

oclusterId = clusterId 

clusterId = _assignClusters(yvec, centers) 

 

if numpy.all(clusterId == oclusterId): 

break 

 

for i in range(nCluster): 

# Only compute func if some points are available; otherwise, default to NaN. 

pointsInCluster = (clusterId == i) 

if numpy.any(pointsInCluster): 

centers[i] = func(yvec[pointsInCluster]) 

else: 

centers[i] = numpy.nan 

 

return centers, clusterId 

 

 

def _improveCluster(yvec, centers, clusterId, nsigma=2.0, nIteration=10, clusterNum=0, widthStdAllowed=0.15): 

"""Improve our estimate of one of the clusters (clusterNum) by sigma-clipping around its median""" 

 

nMember = sum(clusterId == clusterNum) 

if nMember < 5: # can't compute meaningful interquartile range, so no chance of improvement 

return clusterId 

for iter in range(nIteration): 

old_nMember = nMember 

 

inCluster0 = clusterId == clusterNum 

yv = yvec[inCluster0] 

 

centers[clusterNum] = numpy.median(yv) 

stdev = numpy.std(yv) 

 

syv = sorted(yv) 

stdev_iqr = 0.741*(syv[int(0.75*nMember)] - syv[int(0.25*nMember)]) 

median = syv[int(0.5*nMember)] 

 

sd = stdev if stdev < stdev_iqr else stdev_iqr 

 

if False: 

print("sigma(iqr) = %.3f, sigma = %.3f" % (stdev_iqr, numpy.std(yv))) 

newCluster0 = abs(yvec - centers[clusterNum]) < nsigma*sd 

clusterId[numpy.logical_and(inCluster0, newCluster0)] = clusterNum 

clusterId[numpy.logical_and(inCluster0, numpy.logical_not(newCluster0))] = -1 

 

nMember = sum(clusterId == clusterNum) 

# 'sd < widthStdAllowed * median' prevents too much rejections 

if nMember == old_nMember or sd < widthStdAllowed * median: 

break 

 

return clusterId 

 

 

def plot(mag, width, centers, clusterId, marker="o", markersize=2, markeredgewidth=0, ltype='-', 

magType="model", clear=True): 

 

log = Log.getLogger("objectSizeStarSelector.plot") 

try: 

import matplotlib.pyplot as plt 

except ImportError as e: 

log.warn("Unable to import matplotlib: %s", e) 

return 

 

global fig 

if not fig: 

fig = plt.figure() 

else: 

if clear: 

fig.clf() 

 

axes = fig.add_axes((0.1, 0.1, 0.85, 0.80)) 

 

xmin = sorted(mag)[int(0.05*len(mag))] 

xmax = sorted(mag)[int(0.95*len(mag))] 

 

axes.set_xlim(-17.5, -13) 

axes.set_xlim(xmin - 0.1*(xmax - xmin), xmax + 0.1*(xmax - xmin)) 

axes.set_ylim(0, 10) 

 

colors = ["r", "g", "b", "c", "m", "k", ] 

for k, mean in enumerate(centers): 

if k == 0: 

axes.plot(axes.get_xlim(), (mean, mean,), "k%s" % ltype) 

 

li = (clusterId == k) 

axes.plot(mag[li], width[li], marker, markersize=markersize, markeredgewidth=markeredgewidth, 

color=colors[k % len(colors)]) 

 

li = (clusterId == -1) 

axes.plot(mag[li], width[li], marker, markersize=markersize, markeredgewidth=markeredgewidth, 

color='k') 

 

if clear: 

axes.set_xlabel("Instrumental %s mag" % magType) 

axes.set_ylabel(r"$\sqrt{(I_{xx} + I_{yy})/2}$") 

 

return fig 

 

## @addtogroup LSST_task_documentation 

## @{ 

## @page ObjectSizeStarSelectorTask 

## @ref ObjectSizeStarSelectorTask_ "ObjectSizeStarSelectorTask" 

## @copybrief ObjectSizeStarSelectorTask 

## @} 

 

 

@pexConfig.registerConfigurable("objectSize", sourceSelectorRegistry) 

class ObjectSizeStarSelectorTask(BaseSourceSelectorTask): 

"""!A star selector that looks for a cluster of small objects in a size-magnitude plot 

 

@anchor ObjectSizeStarSelectorTask_ 

 

@section meas_algorithms_objectSizeStarSelector_Contents Contents 

 

- @ref meas_algorithms_objectSizeStarSelector_Purpose 

- @ref meas_algorithms_objectSizeStarSelector_Initialize 

- @ref meas_algorithms_objectSizeStarSelector_IO 

- @ref meas_algorithms_objectSizeStarSelector_Config 

- @ref meas_algorithms_objectSizeStarSelector_Debug 

 

@section meas_algorithms_objectSizeStarSelector_Purpose Description 

 

A star selector that looks for a cluster of small objects in a size-magnitude plot. 

 

@section meas_algorithms_objectSizeStarSelector_Initialize Task initialisation 

 

@copydoc \_\_init\_\_ 

 

@section meas_algorithms_objectSizeStarSelector_IO Invoking the Task 

 

Like all star selectors, the main method is `run`. 

 

@section meas_algorithms_objectSizeStarSelector_Config Configuration parameters 

 

See @ref ObjectSizeStarSelectorConfig 

 

@section meas_algorithms_objectSizeStarSelector_Debug Debug variables 

 

ObjectSizeStarSelectorTask has a debug dictionary with the following keys: 

<dl> 

<dt>display 

<dd>bool; if True display debug information 

<dt>displayExposure 

<dd>bool; if True display the exposure and spatial cells 

<dt>plotMagSize 

<dd>bool: if True display the magnitude-size relation using matplotlib 

<dt>dumpData 

<dd>bool; if True dump data to a pickle file 

</dl> 

 

For example, put something like: 

@code{.py} 

import lsstDebug 

def DebugInfo(name): 

di = lsstDebug.getInfo(name) # N.b. lsstDebug.Info(name) would call us recursively 

if name.endswith("objectSizeStarSelector"): 

di.display = True 

di.displayExposure = True 

di.plotMagSize = True 

 

return di 

 

lsstDebug.Info = DebugInfo 

@endcode 

into your `debug.py` file and run your task with the `--debug` flag. 

""" 

ConfigClass = ObjectSizeStarSelectorConfig 

usesMatches = False # selectStars does not use its matches argument 

 

def selectSources(self, sourceCat, matches=None, exposure=None): 

"""Return a selection of PSF candidates that represent likely stars. 

 

A list of PSF candidates may be used by a PSF fitter to construct a PSF. 

 

Parameters: 

----------- 

sourceCat : `lsst.afw.table.SourceCatalog` 

Catalog of sources to select from. 

This catalog must be contiguous in memory. 

matches : `list` of `lsst.afw.table.ReferenceMatch` or None 

Ignored in this SourceSelector. 

exposure : `lsst.afw.image.Exposure` or None 

The exposure the catalog was built from; used to get the detector 

to transform to TanPix, and for debug display. 

 

Return 

------ 

struct : `lsst.pipe.base.Struct` 

The struct contains the following data: 

 

- selected : `array` of `bool`` 

Boolean array of sources that were selected, same length as 

sourceCat. 

""" 

import lsstDebug 

display = lsstDebug.Info(__name__).display 

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

plotMagSize = lsstDebug.Info(__name__).plotMagSize # display the magnitude-size relation 

dumpData = lsstDebug.Info(__name__).dumpData # dump data to pickle file? 

 

detector = exposure.getDetector() 

pixToTanPix = None 

if detector is not None: 

pixToTanPix = detector.getTransform(PIXELS, TAN_PIXELS) 

# 

# Look at the distribution of stars in the magnitude-size plane 

# 

flux = sourceCat.get(self.config.sourceFluxField) 

 

xx = numpy.empty(len(sourceCat)) 

xy = numpy.empty_like(xx) 

yy = numpy.empty_like(xx) 

for i, source in enumerate(sourceCat): 

Ixx, Ixy, Iyy = source.getIxx(), source.getIxy(), source.getIyy() 

if pixToTanPix: 

p = lsst.geom.Point2D(source.getX(), source.getY()) 

linTransform = afwGeom.linearizeTransform(pixToTanPix, p).getLinear() 

m = afwGeom.Quadrupole(Ixx, Iyy, Ixy) 

m.transform(linTransform) 

Ixx, Iyy, Ixy = m.getIxx(), m.getIyy(), m.getIxy() 

 

xx[i], xy[i], yy[i] = Ixx, Ixy, Iyy 

 

width = numpy.sqrt(0.5*(xx + yy)) 

with numpy.errstate(invalid="ignore"): # suppress NAN warnings 

bad = reduce(lambda x, y: numpy.logical_or(x, sourceCat.get(y)), self.config.badFlags, False) 

bad = numpy.logical_or(bad, flux < self.config.fluxMin) 

bad = numpy.logical_or(bad, numpy.logical_not(numpy.isfinite(width))) 

bad = numpy.logical_or(bad, numpy.logical_not(numpy.isfinite(flux))) 

bad = numpy.logical_or(bad, width < self.config.widthMin) 

bad = numpy.logical_or(bad, width > self.config.widthMax) 

if self.config.fluxMax > 0: 

bad = numpy.logical_or(bad, flux > self.config.fluxMax) 

good = numpy.logical_not(bad) 

 

if not numpy.any(good): 

raise RuntimeError("No objects passed our cuts for consideration as psf stars") 

 

mag = -2.5*numpy.log10(flux[good]) 

width = width[good] 

# 

# Look for the maximum in the size histogram, then search upwards for the minimum that separates 

# the initial peak (of, we presume, stars) from the galaxies 

# 

if dumpData: 

import os 

import pickle as pickle 

_ii = 0 

while True: 

pickleFile = os.path.expanduser(os.path.join("~", "widths-%d.pkl" % _ii)) 

if not os.path.exists(pickleFile): 

break 

_ii += 1 

 

with open(pickleFile, "wb") as fd: 

pickle.dump(mag, fd, -1) 

pickle.dump(width, fd, -1) 

 

centers, clusterId = _kcenters(width, nCluster=4, useMedian=True, 

widthStdAllowed=self.config.widthStdAllowed) 

 

if display and plotMagSize: 

fig = plot(mag, width, centers, clusterId, 

magType=self.config.sourceFluxField.split(".")[-1].title(), 

marker="+", markersize=3, markeredgewidth=None, ltype=':', clear=True) 

else: 

fig = None 

 

clusterId = _improveCluster(width, centers, clusterId, 

nsigma=self.config.nSigmaClip, 

widthStdAllowed=self.config.widthStdAllowed) 

 

if display and plotMagSize: 

plot(mag, width, centers, clusterId, marker="x", markersize=3, markeredgewidth=None, clear=False) 

 

stellar = (clusterId == 0) 

# 

# We know enough to plot, if so requested 

# 

frame = 0 

 

if fig: 

if display and displayExposure: 

ds9.mtv(exposure.getMaskedImage(), frame=frame, title="PSF candidates") 

 

global eventHandler 

eventHandler = EventHandler(fig.get_axes()[0], mag, width, 

sourceCat.getX()[good], sourceCat.getY()[good], frames=[frame]) 

 

fig.show() 

 

while True: 

try: 

reply = input("continue? [c h(elp) q(uit) p(db)] ").strip() 

except EOFError: 

reply = None 

if not reply: 

reply = "c" 

 

if reply: 

if reply[0] == "h": 

print("""\ 

We cluster the points; red are the stellar candidates and the other colours are other clusters. 

Points labelled + are rejects from the cluster (only for cluster 0). 

 

At this prompt, you can continue with almost any key; 'p' enters pdb, and 'h' prints this text 

 

If displayExposure is true, you can put the cursor on a point and hit 'p' to see it in ds9. 

""") 

elif reply[0] == "p": 

import pdb 

pdb.set_trace() 

elif reply[0] == 'q': 

sys.exit(1) 

else: 

break 

 

if display and displayExposure: 

mi = exposure.getMaskedImage() 

 

with ds9.Buffering(): 

for i, source in enumerate(sourceCat): 

if good[i]: 

ctype = ds9.GREEN # star candidate 

else: 

ctype = ds9.RED # not star 

 

ds9.dot("+", source.getX() - mi.getX0(), 

source.getY() - mi.getY0(), frame=frame, ctype=ctype) 

 

# stellar only applies to good==True objects 

mask = good == True # noqa (numpy bool comparison): E712 

good[mask] = stellar 

 

return Struct(selected=good)