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

# This file is part of obs_base. 

# 

# Developed for the LSST Data Management System. 

# This product includes software developed by the LSST Project 

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

 

__all__ = ("FitsRawFormatterBase",) 

 

from abc import ABCMeta, abstractmethod 

 

from astro_metadata_translator import ObservationInfo 

 

import lsst.afw.fits 

import lsst.afw.geom 

import lsst.afw.image 

from lsst.daf.butler import FileDescriptor 

from lsst.daf.butler.formatters.fitsExposureFormatter import FitsExposureFormatter 

import lsst.log 

 

from lsst.obs.base import MakeRawVisitInfoViaObsInfo 

from lsst.obs.base.utils import createInitialSkyWcs, InitialSkyWcsError 

 

 

class FitsRawFormatterBase(FitsExposureFormatter, metaclass=ABCMeta): 

"""Abstract base class for reading and writing raw data to and from 

FITS files. 

""" 

 

def __init__(self, *args, **kwargs): 

self.filterDefinitions.defineFilters() 

super().__init__(*args, **kwargs) 

 

@classmethod 

def fromMetadata(cls, metadata, obsInfo=None, storageClass=None, location=None): 

"""Construct a possibly-limited formatter from known metadata. 

 

Parameters 

---------- 

metadata : `lsst.daf.base.PropertyList` 

Raw header metadata, with any fixes (see 

`astro_metadata_translator.fix_header`) applied but nothing 

stripped. 

obsInfo : `astro_metadata_translator.ObservationInfo`, optional 

Structured information already extracted from ``metadata``. 

If not provided, will be read from ``metadata`` on first use. 

storageClass : `lsst.daf.butler.StorageClass`, optional 

StorageClass for this file. If not provided, the formatter will 

only support `makeWcs`, `makeVisitInfo`, `makeFilter`, and other 

operations that operate purely on metadata and not the actual file. 

location : `lsst.daf.butler.Location`, optional. 

Location of the file. If not provided, the formatter will only 

support `makeWcs`, `makeVisitInfo`, `makeFilter`, and other 

operations that operate purely on metadata and not the actual file. 

 

Returns 

------- 

formatter : `FitsRawFormatterBase` 

An instance of ``cls``. 

""" 

self = cls(FileDescriptor(location, storageClass)) 

self._metadata = metadata 

self._observationInfo = obsInfo 

return self 

 

@property 

@abstractmethod 

def translatorClass(self): 

"""`~astro_metadata_translator.MetadataTranslator` to translate 

metadata header to `~astro_metadata_translator.ObservationInfo`. 

""" 

return None 

 

_observationInfo = None 

 

@property 

@abstractmethod 

def filterDefinitions(self): 

"""`~lsst.obs.base.FilterDefinitions`, defining the filters for this 

instrument. 

""" 

return None 

 

def readImage(self): 

"""Read just the image component of the Exposure. 

 

Returns 

------- 

image : `~lsst.afw.image.Image` 

In-memory image component. 

""" 

return lsst.afw.image.ImageU(self.fileDescriptor.location.path) 

 

def readMask(self): 

"""Read just the mask component of the Exposure. 

 

May return None (as the default implementation does) to indicate that 

there is no mask information to be extracted (at least not trivially) 

from the raw data. This will prohibit direct reading of just the mask, 

and set the mask of the full Exposure to zeros. 

 

Returns 

------- 

mask : `~lsst.afw.image.Mask` 

In-memory mask component. 

""" 

return None 

 

def readVariance(self): 

"""Read just the variance component of the Exposure. 

 

May return None (as the default implementation does) to indicate that 

there is no variance information to be extracted (at least not 

trivially) from the raw data. This will prohibit direct reading of 

just the variance, and set the variance of the full Exposure to zeros. 

 

Returns 

------- 

image : `~lsst.afw.image.Image` 

In-memory variance component. 

""" 

return None 

 

def isOnSky(self): 

"""Boolean to determine if the exposure is thought to be on the sky. 

 

Returns 

------- 

onSky : `bool` 

Returns `True` if the observation looks like it was taken on the 

sky. Returns `False` if this observation looks like a calibration 

observation. 

 

Notes 

----- 

If there is tracking RA/Dec information associated with the 

observation it is assumed that the observation is on sky. 

Currently the observation type is not checked. 

""" 

if self.observationInfo.tracking_radec is None: 

return False 

return True 

 

def stripMetadata(self): 

"""Remove metadata entries that are parsed into components. 

""" 

# NOTE: makeVisitInfo() may not strip any metadata itself, but calling 

# it ensures that ObservationInfo is created from the metadata, which 

# will strip the VisitInfo keys and more. 

self.makeVisitInfo() 

self._createSkyWcsFromMetadata() 

 

def makeVisitInfo(self): 

"""Construct a VisitInfo from metadata. 

 

Returns 

------- 

visitInfo : `~lsst.afw.image.VisitInfo` 

Structured metadata about the observation. 

""" 

return MakeRawVisitInfoViaObsInfo.observationInfo2visitInfo(self.observationInfo) 

 

@abstractmethod 

def getDetector(self, id): 

"""Return the detector that acquired this raw exposure. 

 

Parameters 

---------- 

id : `int` 

The identifying number of the detector to get. 

 

Returns 

------- 

detector : `~lsst.afw.cameraGeom.Detector` 

The detector associated with that ``id``. 

""" 

raise NotImplementedError("Must be implemented by subclasses.") 

 

def makeWcs(self, visitInfo, detector): 

"""Create a SkyWcs from information about the exposure. 

 

If VisitInfo is not None, use it and the detector to create a SkyWcs, 

otherwise return the metadata-based SkyWcs (always created, so that 

the relevant metadata keywords are stripped). 

 

Parameters 

---------- 

visitInfo : `~lsst.afw.image.VisitInfo` 

The information about the telescope boresight and camera 

orientation angle for this exposure. 

detector : `~lsst.afw.cameraGeom.Detector` 

The detector used to acquire this exposure. 

 

Returns 

------- 

skyWcs : `~lsst.afw.geom.SkyWcs` 

Reversible mapping from pixel coordinates to sky coordinates. 

 

Raises 

------ 

InitialSkyWcsError 

Raised if there is an error generating the SkyWcs, chained from the 

lower-level exception if available. 

""" 

if not self.isOnSky(): 

# This is not an on-sky observation 

return None 

 

skyWcs = self._createSkyWcsFromMetadata() 

 

log = lsst.log.Log.getLogger("fitsRawFormatter") 

if visitInfo is None: 

msg = "No VisitInfo; cannot access boresight information. Defaulting to metadata-based SkyWcs." 

log.warn(msg) 

if skyWcs is None: 

raise InitialSkyWcsError("Failed to create both metadata and boresight-based SkyWcs." 

"See warnings in log messages for details.") 

return skyWcs 

skyWcs = createInitialSkyWcs(visitInfo, detector) 

 

return skyWcs 

 

def _createSkyWcsFromMetadata(self): 

"""Create a SkyWcs from the FITS header metadata in an Exposure. 

 

Returns 

------- 

skyWcs: `lsst.afw.geom.SkyWcs`, or None 

The WCS that was created from ``self.metadata``, or None if that 

creation fails due to invalid metadata. 

""" 

if not self.isOnSky(): 

# This is not an on-sky observation 

return None 

 

try: 

return lsst.afw.geom.makeSkyWcs(self.metadata, strip=True) 

except TypeError as e: 

log = lsst.log.Log.getLogger("fitsRawFormatter") 

log.warn("Cannot create a valid WCS from metadata: %s", e.args[0]) 

return None 

 

def makeFilter(self): 

"""Construct a Filter from metadata. 

 

Returns 

------- 

filter : `~lsst.afw.image.Filter` 

Object that identifies the filter for this image. 

 

Raises 

------ 

NotFoundError 

Raised if the physical filter was not registered via 

`~lsst.afw.image.utils.defineFilter`. 

""" 

return lsst.afw.image.Filter(self.observationInfo.physical_filter) 

 

def readImageComponent(self, component): 

"""Read the image, mask, or variance component of an Exposure. 

 

Parameters 

---------- 

component : `str`, optional 

Component to read from the file. Always one of "image", 

"variance", or "mask". 

 

Returns 

------- 

image : `~lsst.afw.image.Image` or `~lsst.afw.image.Mask` 

In-memory image, variance, or mask component. 

""" 

if component == "image": 

return self.readImage() 

elif component == "mask": 

return self.readMask() 

elif component == "variance": 

return self.readVariance() 

 

def readInfoComponent(self, component): 

"""Read a component held by ExposureInfo. 

 

The implementation provided by FitsRawFormatter provides only "wcs" 

and "visitInfo". When adding support for other components, subclasses 

should delegate to `super()` for those and update `readFull` with 

similar logic. 

 

Parameters 

---------- 

component : `str`, optional 

Component to read from the file. 

 

Returns 

------- 

obj : component-dependent 

In-memory component object. 

""" 

if component == "filter": 

return self.makeFilter() 

elif component == "visitInfo": 

return self.makeVisitInfo() 

elif component == "wcs": 

detector = self.getDetector(self.observationInfo.detector_num) 

visitInfo = self.makeVisitInfo() 

return self.makeWcs(visitInfo, detector) 

return None 

 

def readFull(self, parameters=None): 

"""Read the full Exposure object. 

 

Parameters 

---------- 

parameters : `dict`, optional 

If specified, a dictionary of slicing parameters that overrides 

those in the `fileDescriptor` attribute. 

 

Returns 

------- 

exposure : `~lsst.afw.image.Exposure` 

Complete in-memory exposure. 

""" 

from lsst.afw.image import makeExposure, makeMaskedImage 

full = makeExposure(makeMaskedImage(self.readImage())) 

mask = self.readMask() 

if mask is not None: 

full.setMask(mask) 

variance = self.readVariance() 

if variance is not None: 

full.setVariance(variance) 

full.setDetector(self.getDetector(self.observationInfo.detector_num)) 

info = full.getInfo() 

info.setFilter(self.makeFilter()) 

info.setVisitInfo(self.makeVisitInfo()) 

info.setWcs(self.makeWcs(info.getVisitInfo(), info.getDetector())) 

# We don't need to call stripMetadata() here because it has already 

# been stripped during creation of the ObservationInfo, WCS, etc. 

full.setMetadata(self.metadata) 

return full 

 

def readRawHeaderWcs(self, parameters=None): 

"""Read the SkyWcs stored in the un-modified raw FITS WCS header keys. 

""" 

return lsst.afw.geom.makeSkyWcs(lsst.afw.fits.readMetadata(self.fileDescriptor)) 

 

def write(self, inMemoryDataset): 

"""Write a Python object to a file. 

 

Parameters 

---------- 

inMemoryDataset : `object` 

The Python object to store. 

 

Returns 

------- 

path : `str` 

The `URI` where the primary file is stored. 

""" 

raise NotImplementedError("Raw data cannot be `put`.") 

 

@property 

def observationInfo(self): 

"""The `~astro_metadata_translator.ObservationInfo` extracted from 

this file's metadata (`~astro_metadata_translator.ObservationInfo`, 

read-only). 

""" 

if self._observationInfo is None: 

self._observationInfo = ObservationInfo(self.metadata, translator_class=self.translatorClass) 

return self._observationInfo