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

# 

# LSST Data Management System 

# Copyright 2008-2016 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 <http://www.lsstcorp.org/LegalNotices/>. 

# 

__all__ = ["ANetAstrometryConfig", "ANetAstrometryTask", "showAstrometry"] 

 

import numpy as np 

 

import lsstDebug 

import lsst.pex.exceptions 

from lsst.afw.cameraGeom import PIXELS, TAN_PIXELS 

from lsst.afw.table import Point2DKey, CovarianceMatrix2fKey, updateSourceCoords 

import lsst.geom as geom 

import lsst.pex.config as pexConfig 

import lsst.pipe.base as pipeBase 

from lsst.meas.astrom import displayAstrometry 

from lsst.meas.astrom.sip import makeCreateWcsWithSip 

from .anetBasicAstrometry import ANetBasicAstrometryTask 

 

 

class ANetAstrometryConfig(pexConfig.Config): 

solver = pexConfig.ConfigurableField( 

target=ANetBasicAstrometryTask, 

doc="Basic astrometry solver", 

) 

forceKnownWcs = pexConfig.Field(dtype=bool, doc=( 

"Assume that the input image's WCS is correct, without comparing it to any external reality." 

" (In contrast to using Astrometry.net). NOTE, if you set this, you probably also want to" 

" un-set 'solver.calculateSip'; otherwise we'll still try to find a TAN-SIP WCS starting " 

" from the existing WCS"), default=False) 

rejectThresh = pexConfig.RangeField(dtype=float, default=3.0, doc="Rejection threshold for Wcs fitting", 

min=0.0, inclusiveMin=False) 

rejectIter = pexConfig.RangeField(dtype=int, default=3, doc="Rejection iterations for Wcs fitting", 

min=0) 

 

@property 

def refObjLoader(self): 

"""An alias, for a uniform interface with the standard AstrometryTask""" 

return self.solver 

 

# \addtogroup LSST_task_documentation 

# \{ 

# \page measAstrom_anetAstrometryTask 

# \ref ANetAstrometryTask_ "ANetAstrometryTask" 

# Use astrometry.net to match input sources with a reference catalog and solve for the Wcs 

# \} 

 

 

class ANetAstrometryTask(pipeBase.Task): 

r"""!Use astrometry.net to match input sources with a reference catalog and solve for the Wcs 

 

@anchor ANetAstrometryTask_ 

 

The actual matching and solving is done by the 'solver'; this Task 

serves as a wrapper for taking into account the known optical distortion. 

 

\section pipe_tasks_astrometry_Contents Contents 

 

- \ref pipe_tasks_astrometry_Purpose 

- \ref pipe_tasks_astrometry_Initialize 

- \ref pipe_tasks_astrometry_IO 

- \ref pipe_tasks_astrometry_Config 

- \ref pipe_tasks_astrometry_Debug 

- \ref pipe_tasks_astrometry_Example 

 

\section pipe_tasks_astrometry_Purpose Description 

 

\copybrief ANetAstrometryTask 

 

\section pipe_tasks_astrometry_Initialize Task initialisation 

 

\copydoc \_\_init\_\_ 

 

\section pipe_tasks_astrometry_IO Invoking the Task 

 

\copydoc run 

 

\section pipe_tasks_astrometry_Config Configuration parameters 

 

See \ref ANetAstrometryConfig 

 

\section pipe_tasks_astrometry_Debug Debug variables 

 

The \link lsst.pipe.base.cmdLineTask.CmdLineTask command line task\endlink interface supports a 

flag \c -d to import \b debug.py from your \c PYTHONPATH; 

see \ref baseDebug for more about \b debug.py files. 

 

The available variables in ANetAstrometryTask are: 

<DL> 

<DT> \c display 

<DD> If True call showAstrometry while iterating ANetAstrometryConfig.rejectIter times, 

and also after converging; and call displayAstrometry after applying the distortion correction. 

<DT> \c frame 

<DD> display frame to use in showAstrometry and displayAstrometry 

<DT> \c pause 

<DD> Pause after showAstrometry and displayAstrometry? 

</DL> 

 

\section pipe_tasks_astrometry_Example A complete example of using ANetAstrometryTask 

 

See \ref pipe_tasks_photocal_Example. 

 

To investigate the \ref pipe_tasks_astrometry_Debug, 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 in ("lsst.pipe.tasks.anetAstrometry", "lsst.pipe.tasks.anetBasicAstrometry"): 

di.display = 1 

di.frame = 1 

di.pause = True 

 

return di 

 

lsstDebug.Info = DebugInfo 

\endcode 

into your debug.py file and run photoCalTask.py with the \c --debug flag. 

""" 

ConfigClass = ANetAstrometryConfig 

_DefaultName = "astrometricSolver" 

 

def __init__(self, schema, refObjLoader=None, **kwds): 

r"""!Create the astrometric calibration task. Most arguments are simply passed onto pipe.base.Task. 

 

\param schema An lsst::afw::table::Schema used to create the output lsst.afw.table.SourceCatalog 

\param refObjLoader The AstrometryTask constructor requires a refObjLoader. In order to make this 

task retargettable for AstrometryTask it needs to take the same arguments. This argument will be 

ignored since it uses its own internal loader. 

\param **kwds keyword arguments to be passed to the lsst.pipe.base.task.Task constructor 

 

A centroid field "centroid.distorted" (used internally during the Task's operation) 

will be added to the schema. 

""" 

pipeBase.Task.__init__(self, **kwds) 

self.distortedName = "astrom_distorted" 

self.centroidXKey = schema.addField(self.distortedName + "_x", type="D", 

doc="centroid distorted for astrometry solver") 

self.centroidYKey = schema.addField(self.distortedName + "_y", type="D", 

doc="centroid distorted for astrometry solver") 

self.centroidXErrKey = schema.addField(self.distortedName + "_xErr", type="F", 

doc="centroid distorted err for astrometry solver") 

self.centroidYErrKey = schema.addField(self.distortedName + "_yErr", type="F", 

doc="centroid distorted err for astrometry solver") 

self.centroidFlagKey = schema.addField(self.distortedName + "_flag", type="Flag", 

doc="centroid distorted flag astrometry solver") 

self.centroidKey = Point2DKey(self.centroidXKey, self.centroidYKey) 

self.centroidErrKey = CovarianceMatrix2fKey((self.centroidXErrKey, self.centroidYErrKey)) 

# postpone making the solver subtask because it may not be needed and is expensive to create 

self.solver = None 

 

@pipeBase.timeMethod 

def run(self, exposure, sourceCat): 

"""!Load reference objects, match sources and optionally fit a WCS 

 

This is a thin layer around solve or loadAndMatch, depending on config.forceKnownWcs 

 

@param[in,out] exposure exposure whose WCS is to be fit 

The following are read only: 

- bbox 

- photoCalib (may be absent) 

- filter (may be unset) 

- detector (if wcs is pure tangent; may be absent) 

The following are updated: 

- wcs (the initial value is used as an initial guess, and is required) 

@param[in] sourceCat catalog of sourceCat detected on the exposure (an lsst.afw.table.SourceCatalog) 

@return an lsst.pipe.base.Struct with these fields: 

- refCat reference object catalog of objects that overlap the exposure (with some margin) 

(an lsst::afw::table::SimpleCatalog) 

- matches astrometric matches, a list of lsst.afw.table.ReferenceMatch 

- matchMeta metadata about the field (an lsst.daf.base.PropertyList) 

""" 

if self.config.forceKnownWcs: 

return self.loadAndMatch(exposure=exposure, sourceCat=sourceCat) 

else: 

return self.solve(exposure=exposure, sourceCat=sourceCat) 

 

@pipeBase.timeMethod 

def solve(self, exposure, sourceCat): 

r"""!Match with reference sources and calculate an astrometric solution 

 

\param[in,out] exposure Exposure to calibrate; wcs is updated 

\param[in] sourceCat catalog of measured sources (an lsst.afw.table.SourceCatalog) 

\return a pipeBase.Struct with fields: 

- refCat reference object catalog of objects that overlap the exposure (with some margin) 

(an lsst::afw::table::SimpleCatalog) 

- matches astrometric matches, a list of lsst.afw.table.ReferenceMatch 

- matchMeta metadata about the field (an lsst.daf.base.PropertyList) 

 

The reference catalog actually used is up to the implementation 

of the solver; it will be manifested in the returned matches as 

a list of lsst.afw.table.ReferenceMatch objects (\em i.e. of lsst.afw.table.Match with 

\c first being of type lsst.afw.table.SimpleRecord and \c second type lsst.afw.table.SourceRecord --- 

the reference object and matched object respectively). 

 

\note 

The input sources have the centroid slot moved to a new column "centroid.distorted" 

which has the positions corrected for any known optical distortion; 

the 'solver' (which is instantiated in the 'astrometry' member) 

should therefore simply use the centroids provided by calling 

afw.table.Source.getCentroid() on the individual source records. This column \em must 

be present in the sources table. 

 

\note ignores config.forceKnownWcs 

""" 

results = self._astrometry(sourceCat=sourceCat, exposure=exposure) 

 

if results.matches: 

self.refitWcs(sourceCat=sourceCat, exposure=exposure, matches=results.matches) 

 

return results 

 

@pipeBase.timeMethod 

def distort(self, sourceCat, exposure): 

r"""!Calculate distorted source positions 

 

CCD images are often affected by optical distortion that makes 

the astrometric solution higher order than linear. Unfortunately, 

most (all?) matching algorithms require that the distortion be 

small or zero, and so it must be removed. We do this by calculating 

(un-)distorted positions, based on a known optical distortion model 

in the Ccd. 

 

The distortion correction moves sources, so we return the distorted bounding box. 

 

\param[in] exposure Exposure to process 

\param[in,out] sourceCat SourceCatalog; getX() and getY() will be used as inputs, 

with distorted points in "centroid.distorted" field. 

\return bounding box of distorted exposure 

""" 

detector = exposure.getDetector() 

pixToTanXYTransform = None 

if detector is None: 

self.log.warn("No detector associated with exposure; assuming null distortion") 

else: 

pixToTanXYTransform = detector.getTransform(PIXELS, TAN_PIXELS) 

 

if pixToTanXYTransform is None: 

self.log.info("Null distortion correction") 

for s in sourceCat: 

s.set(self.centroidKey, s.getCentroid()) 

s.set(self.centroidErrKey, s.getCentroidErr()) 

s.set(self.centroidFlagKey, s.getCentroidFlag()) 

return exposure.getBBox() 

 

# Distort source positions 

self.log.info("Applying distortion correction") 

for s in sourceCat: 

centroid = pixToTanXYTransform.forwardTransform(s.getCentroid()) 

s.set(self.centroidKey, centroid) 

s.set(self.centroidErrKey, s.getCentroidErr()) 

s.set(self.centroidFlagKey, s.getCentroidFlag()) 

 

# Get distorted image size so that astrometry_net does not clip. 

bboxD = geom.Box2D() 

for corner in detector.getCorners(TAN_PIXELS): 

bboxD.include(corner) 

 

if lsstDebug.Info(__name__).display: 

frame = lsstDebug.Info(__name__).frame 

pause = lsstDebug.Info(__name__).pause 

displayAstrometry(sourceCat=sourceCat, distortedCentroidKey=self.centroidKey, 

exposure=exposure, frame=frame, pause=pause) 

 

return geom.Box2I(bboxD) 

 

@pipeBase.timeMethod 

def loadAndMatch(self, exposure, sourceCat, bbox=None): 

"""!Load reference objects overlapping an exposure and match to sources detected on that exposure 

 

@param[in] exposure exposure whose WCS is to be fit 

@param[in] sourceCat catalog of sourceCat detected on the exposure (an lsst.afw.table.SourceCatalog) 

@param[in] bbox bounding box go use for finding reference objects; if None, use exposure's bbox 

 

@return an lsst.pipe.base.Struct with these fields: 

- refCat reference object catalog of objects that overlap the exposure (with some margin) 

(an lsst::afw::table::SimpleCatalog) 

- matches astrometric matches, a list of lsst.afw.table.ReferenceMatch 

- matchMeta metadata about the field (an lsst.daf.base.PropertyList) 

 

@note ignores config.forceKnownWcs 

""" 

bbox = exposure.getBBox() 

if not self.solver: 

self.makeSubtask("solver") 

 

astrom = self.solver.useKnownWcs( 

sourceCat=sourceCat, 

exposure=exposure, 

bbox=bbox, 

calculateSip=False, 

) 

 

if astrom is None or astrom.getWcs() is None: 

raise RuntimeError("Unable to solve astrometry") 

 

matches = astrom.getMatches() 

matchMeta = astrom.getMatchMetadata() 

if matches is None or len(matches) == 0: 

raise RuntimeError("No astrometric matches") 

self.log.info("%d astrometric matches", len(matches)) 

 

if self._display: 

frame = lsstDebug.Info(__name__).frame 

displayAstrometry(exposure=exposure, sourceCat=sourceCat, matches=matches, 

frame=frame, pause=False) 

 

return pipeBase.Struct( 

refCat=astrom.refCat, 

matches=matches, 

matchMeta=matchMeta, 

) 

 

@pipeBase.timeMethod 

def _astrometry(self, sourceCat, exposure, bbox=None): 

r"""!Solve astrometry to produce WCS 

 

\param[in] sourceCat Sources on exposure, an lsst.afw.table.SourceCatalog 

\param[in,out] exposure Exposure to process, an lsst.afw.image.ExposureF or D; wcs is updated 

\param[in] bbox Bounding box, or None to use exposure 

\return a pipe.base.Struct with fields: 

- refCat reference object catalog of objects that overlap the exposure (with some margin) 

(an lsst::afw::table::SimpleCatalog) 

- matches astrometric matches, a list of lsst.afw.table.ReferenceMatch 

- matchMeta metadata about the field (an lsst.daf.base.PropertyList) 

""" 

self.log.info("Solving astrometry") 

if bbox is None: 

bbox = exposure.getBBox() 

 

if not self.solver: 

self.makeSubtask("solver") 

 

astrom = self.solver.determineWcs(sourceCat=sourceCat, exposure=exposure, bbox=bbox) 

 

if astrom is None or astrom.getWcs() is None: 

raise RuntimeError("Unable to solve astrometry") 

 

matches = astrom.getMatches() 

matchMeta = astrom.getMatchMetadata() 

if matches is None or len(matches) == 0: 

raise RuntimeError("No astrometric matches") 

self.log.info("%d astrometric matches", len(matches)) 

 

# Note that this is the Wcs for the provided positions, which may be distorted 

exposure.setWcs(astrom.getWcs()) 

 

if self._display: 

frame = lsstDebug.Info(__name__).frame 

displayAstrometry(exposure=exposure, sourceCat=sourceCat, matches=matches, 

frame=frame, pause=False) 

 

return pipeBase.Struct( 

refCat=astrom.refCat, 

matches=matches, 

matchMeta=matchMeta, 

) 

 

@pipeBase.timeMethod 

def refitWcs(self, sourceCat, exposure, matches): 

"""!A final Wcs solution after matching and removing distortion 

 

Specifically, fitting the non-linear part, since the linear 

part has been provided by the matching engine. 

 

@param sourceCat Sources on exposure, an lsst.afw.table.SourceCatalog 

@param exposure Exposure of interest, an lsst.afw.image.ExposureF or D 

@param matches Astrometric matches, as a list of lsst.afw.table.ReferenceMatch 

 

@return the resolved-Wcs object, or None if config.solver.calculateSip is False. 

""" 

sip = None 

if self.config.solver.calculateSip: 

self.log.info("Refitting WCS") 

origMatches = matches 

wcs = exposure.getWcs() 

 

import lsstDebug 

display = lsstDebug.Info(__name__).display 

frame = lsstDebug.Info(__name__).frame 

pause = lsstDebug.Info(__name__).pause 

 

def fitWcs(initialWcs, title=None): 

"""!Do the WCS fitting and display of the results""" 

sip = makeCreateWcsWithSip(matches, initialWcs, self.config.solver.sipOrder) 

resultWcs = sip.getNewWcs() 

if display: 

showAstrometry(exposure, resultWcs, origMatches, matches, frame=frame, 

title=title, pause=pause) 

return resultWcs, sip.getScatterOnSky() 

 

numRejected = 0 

try: 

for i in range(self.config.rejectIter): 

wcs, scatter = fitWcs(wcs, title="Iteration %d" % i) 

 

ref = np.array([wcs.skyToPixel(m.first.getCoord()) for m in matches]) 

src = np.array([m.second.getCentroid() for m in matches]) 

diff = ref - src 

rms = diff.std() 

trimmed = [] 

for d, m in zip(diff, matches): 

if np.all(np.abs(d) < self.config.rejectThresh*rms): 

trimmed.append(m) 

else: 

numRejected += 1 

if len(matches) == len(trimmed): 

break 

matches = trimmed 

 

# Final fit after rejection iterations 

wcs, scatter = fitWcs(wcs, title="Final astrometry") 

 

except lsst.pex.exceptions.LengthError as e: 

self.log.warn("Unable to fit SIP: %s", e) 

 

self.log.info("Astrometric scatter: %f arcsec (%d matches, %d rejected)", 

scatter.asArcseconds(), len(matches), numRejected) 

exposure.setWcs(wcs) 

 

# Apply WCS to sources 

updateSourceCoords(wcs, sourceCat) 

else: 

self.log.warn("Not calculating a SIP solution; matches may be suspect") 

 

if self._display: 

frame = lsstDebug.Info(__name__).frame 

displayAstrometry(exposure=exposure, sourceCat=sourceCat, matches=matches, 

frame=frame, pause=False) 

 

return sip 

 

 

def showAstrometry(exposure, wcs, allMatches, useMatches, frame=0, title=None, pause=False): 

r"""!Show results of astrometry fitting 

 

\param exposure Image to display 

\param wcs Astrometric solution 

\param allMatches List of all astrometric matches (including rejects) 

\param useMatches List of used astrometric matches 

\param frame Frame number for display 

\param title Title for display 

\param pause Pause to allow viewing of the display and optional debugging? 

 

- Matches are shown in yellow if used in the Wcs solution, otherwise red 

- +: Detected objects 

- x: Catalogue objects 

""" 

import lsst.afw.display as afwDisplay 

disp = afwDisplay.Display(frame=frame) 

disp.mtv(exposure, title=title) 

 

useIndices = set(m.second.getId() for m in useMatches) 

 

radii = [] 

with disp.Buffering(): 

for i, m in enumerate(allMatches): 

x, y = m.second.getX(), m.second.getY() 

pix = wcs.skyToPixel(m.first.getCoord()) 

 

isUsed = m.second.getId() in useIndices 

if isUsed: 

radii.append(np.hypot(pix[0] - x, pix[1] - y)) 

 

color = afwDisplay.YELLOW if isUsed else afwDisplay.RED 

 

disp.dot("+", x, y, size=10, ctype=color) 

disp.dot("x", pix[0], pix[1], size=10, ctype=color) 

 

radii = np.array(radii) 

print("<dr> = %.4g +- %.4g pixels [%d/%d matches]" % (radii.mean(), radii.std(), 

len(useMatches), len(allMatches))) 

 

if pause: 

import sys 

while True: 

try: 

reply = input("Debugging? [p]db [q]uit; any other key to continue... ").strip() 

except EOFError: 

reply = "" 

 

if len(reply) > 1: 

reply = reply[0] 

if reply == "p": 

import pdb 

pdb.set_trace() 

elif reply == "q": 

sys.exit(1) 

else: 

break