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

# This file is part of afw. 

# 

# Developed for the LSST Data Management System. 

# This product includes software developed by the LSST Project 

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

 

""" 

Tests for MaskedImages 

 

Run with: 

python test_maskedImageIO.py 

or 

pytest test_maskedImageIO.py 

""" 

 

import contextlib 

import itertools 

import os.path 

import unittest 

import shutil 

import tempfile 

 

import numpy as np 

import astropy.io.fits 

 

import lsst.utils 

import lsst.utils.tests 

import lsst.daf.base as dafBase 

import lsst.geom 

import lsst.afw.image as afwImage 

import lsst.afw.math as afwMath 

import lsst.afw.display as afwDisplay 

import lsst.pex.exceptions as pexEx 

 

try: 

dataDir = lsst.utils.getPackageDir("afwdata") 

except pexEx.NotFoundError: 

dataDir = None 

 

try: 

type(display) 

afwDisplay.setDefaultMaskTransparency(75) 

except NameError: 

display = False 

 

 

class MaskedImageTestCase(lsst.utils.tests.TestCase): 

"""A test case for MaskedImage""" 

 

def setUp(self): 

# Set a (non-standard) initial Mask plane definition 

# 

# Ideally we'd use the standard dictionary and a non-standard file, but 

# a standard file's what we have 

# 

self.Mask = afwImage.Mask 

mask = self.Mask() 

 

# Store the default mask planes for later use 

maskPlaneDict = self.Mask().getMaskPlaneDict() 

self.defaultMaskPlanes = sorted( 

maskPlaneDict, key=maskPlaneDict.__getitem__) 

 

# reset so tests will be deterministic 

self.Mask.clearMaskPlaneDict() 

for p in ("ZERO", "BAD", "SAT", "INTRP", "CR", "EDGE"): 

mask.addMaskPlane(p) 

 

if dataDir is not None: 

if False: 

self.fileName = os.path.join(dataDir, "Small_MI.fits") 

else: 

self.fileName = os.path.join( 

dataDir, "CFHT", "D4", "cal-53535-i-797722_1.fits") 

self.mi = afwImage.MaskedImageF(self.fileName) 

 

def tearDown(self): 

if dataDir is not None: 

del self.mi 

# Reset the mask plane to the default 

self.Mask.clearMaskPlaneDict() 

for p in self.defaultMaskPlanes: 

self.Mask.addMaskPlane(p) 

 

@unittest.skipIf(dataDir is None, "afwdata not setup") 

def testFitsRead(self): 

"""Check if we read MaskedImages""" 

 

image = self.mi.getImage() 

mask = self.mi.getMask() 

 

if display: 

afwDisplay.Display(frame=0).mtv(self.mi, title="Image") 

 

self.assertEqual(image[32, 1, afwImage.LOCAL], 3728) 

self.assertEqual(mask[0, 0, afwImage.LOCAL], 2) # == BAD 

 

@unittest.skipIf(dataDir is None, "afwdata not setup") 

def testFitsReadImage(self): 

"""Check if we can read a single-HDU image as a MaskedImage, setting the mask and variance 

planes to zero.""" 

filename = os.path.join(dataDir, "data", "small_img.fits") 

image = afwImage.ImageF(filename) 

maskedImage = afwImage.MaskedImageF(filename) 

exposure = afwImage.ExposureF(filename) 

self.assertEqual(image[0, 0, afwImage.LOCAL], maskedImage.image[0, 0, afwImage.LOCAL]) 

self.assertEqual( 

image[0, 0, afwImage.LOCAL], exposure.getMaskedImage().image[0, 0, afwImage.LOCAL]) 

self.assertTrue(np.all(maskedImage.getMask().getArray() == 0)) 

self.assertTrue( 

np.all(exposure.getMaskedImage().getMask().getArray() == 0)) 

self.assertTrue(np.all(maskedImage.getVariance().getArray() == 0.0)) 

self.assertTrue( 

np.all(exposure.getMaskedImage().getVariance().getArray() == 0.0)) 

 

@unittest.skipIf(dataDir is None, "afwdata not setup") 

def testFitsReadConform(self): 

"""Check if we read MaskedImages and make them replace Mask's plane dictionary""" 

 

metadata, bbox, conformMasks = None, lsst.geom.Box2I(), True 

self.mi = afwImage.MaskedImageF( 

self.fileName, metadata, bbox, afwImage.LOCAL, conformMasks) 

 

image = self.mi.getImage() 

mask = self.mi.getMask() 

 

self.assertEqual(image[32, 1, afwImage.LOCAL], 3728) 

# i.e. not shifted 1 place to the right 

self.assertEqual(mask[0, 0, afwImage.LOCAL], 1) 

 

self.assertEqual(mask.getMaskPlane("CR"), 3, 

"Plane CR has value specified in FITS file") 

 

@unittest.skipIf(dataDir is None, "afwdata not setup") 

def testFitsReadNoConform2(self): 

"""Check that reading a mask doesn't invalidate the plane dictionary""" 

 

testMask = afwImage.Mask(self.fileName, hdu=2) 

 

mask = self.mi.getMask() 

mask |= testMask 

 

@unittest.skipIf(dataDir is None, "afwdata not setup") 

def testFitsReadConform2(self): 

"""Check that conforming a mask invalidates the plane dictionary""" 

 

hdu, metadata, bbox, conformMasks = 2, None, lsst.geom.Box2I(), True 

testMask = afwImage.Mask(self.fileName, 

hdu, metadata, bbox, afwImage.LOCAL, conformMasks) 

 

mask = self.mi.getMask() 

 

def tst(mask=mask): 

mask |= testMask 

 

self.assertRaises(pexEx.RuntimeError, tst) 

 

def testTicket617(self): 

"""Test reading an F64 image and converting it to a MaskedImage""" 

im = afwImage.ImageD(lsst.geom.Extent2I(100, 100)) 

im.set(666) 

afwImage.MaskedImageD(im) 

 

def testReadWriteXY0(self): 

"""Test that we read and write (X0, Y0) correctly""" 

im = afwImage.MaskedImageF(lsst.geom.Extent2I(10, 20)) 

 

x0, y0 = 1, 2 

im.setXY0(x0, y0) 

with lsst.utils.tests.getTempFilePath(".fits") as tmpFile: 

im.writeFits(tmpFile) 

 

im2 = im.Factory(tmpFile) 

self.assertEqual(im2.getX0(), x0) 

self.assertEqual(im2.getY0(), y0) 

 

self.assertEqual(im2.getImage().getX0(), x0) 

self.assertEqual(im2.getImage().getY0(), y0) 

 

self.assertEqual(im2.getMask().getX0(), x0) 

self.assertEqual(im2.getMask().getY0(), y0) 

 

self.assertEqual(im2.getVariance().getX0(), x0) 

self.assertEqual(im2.getVariance().getY0(), y0) 

 

@unittest.skipIf(dataDir is None, "afwdata not setup") 

def testReadFitsWithOptions(self): 

xy0Offset = lsst.geom.Extent2I(7, 5) 

bbox = lsst.geom.Box2I(lsst.geom.Point2I(10, 11), lsst.geom.Extent2I(31, 22)) 

 

with lsst.utils.tests.getTempFilePath(".fits") as filepath: 

# write a temporary version of the image with non-zero XY0 

imagePath = os.path.join(dataDir, "data", "med.fits") 

maskedImage = afwImage.MaskedImageD(imagePath) 

maskedImage.setXY0(lsst.geom.Point2I(xy0Offset)) 

maskedImage.writeFits(filepath) 

 

for ImageClass, imageOrigin in itertools.product( 

(afwImage.MaskedImageF, afwImage.MaskedImageD), 

(None, "LOCAL", "PARENT"), 

): 

with self.subTest(ImageClass=ImageClass, imageOrigin=imageOrigin): 

fullImage = ImageClass(filepath) 

options = dafBase.PropertySet() 

options.set("llcX", bbox.getMinX()) 

options.set("llcY", bbox.getMinY()) 

options.set("width", bbox.getWidth()) 

options.set("height", bbox.getHeight()) 

if imageOrigin is not None: 

options.set("imageOrigin", imageOrigin) 

image1 = ImageClass.readFitsWithOptions(filepath, options) 

readBBoxParent = lsst.geom.Box2I(bbox) 

if imageOrigin == "LOCAL": 

readBBoxParent.shift(xy0Offset) 

self.assertMaskedImagesEqual(image1, ImageClass(fullImage, readBBoxParent)) 

 

for name in ("llcY", "width", "height"): 

badOptions = options.deepCopy() 

badOptions.remove(name) 

with self.assertRaises(pexEx.NotFoundError): 

ImageClass.readFitsWithOptions(filepath, badOptions) 

 

badOptions = options.deepCopy() 

badOptions.set("imageOrigin", "INVALID") 

with self.assertRaises(RuntimeError): 

ImageClass.readFitsWithOptions(filepath, badOptions) 

 

 

@contextlib.contextmanager 

def tmpFits(*hdus): 

# Given a list of numpy arrays, create a temporary FITS file that 

# contains them as consecutive HDUs. Yield it, then remove it. 

hdus = [astropy.io.fits.PrimaryHDU(hdus[0])] + \ 

[astropy.io.fits.ImageHDU(hdu) for hdu in hdus[1:]] 

hdulist = astropy.io.fits.HDUList(hdus) 

tempdir = tempfile.mkdtemp() 

try: 

filename = os.path.join(tempdir, 'test.fits') 

hdulist.writeto(filename) 

yield filename 

finally: 

shutil.rmtree(tempdir) 

 

 

class MultiExtensionTestCase: 

"""Base class for testing that we correctly read multi-extension FITS files. 

 

MEF files may be read to either MaskedImage or Exposure objects. We apply 

the same set of tests to each by subclassing and defining _constructImage 

and _checkImage. 

""" 

# When persisting a MaskedImage (or derivative, e.g. Exposure) to FITS, we impose a data 

# model which the combination of the limits of the FITS structure and the desire to maintain 

# backwards compatibility make it hard to express. We attempt to make this as safe as 

# possible by handling the following situations and logging appropriate warnings: 

# 

# Note that Exposures always set needAllHdus to False. 

# 

# 1. If needAllHdus is true: 

# 1.1 If the user has specified a non-default HDU, we throw. 

# 1.2 If the user has not specified an HDU (or has specified one equal to the default): 

# 1.2.1 If any of the image, mask or variance is unreadable (eg because they don't 

# exist, or they have the wrong data type), we throw. 

# 1.2.2 Otherwise, we return the MaskedImage with image/mask/variance set as 

# expected. 

# 2. If needAllHdus is false: 

# 2.1 If the user has specified a non-default HDU: 

# 2.1.1 If the user specified HDU is unreadable, we throw. 

# 2.1.2 Otherwise, we return the contents of that HDU as the image and default 

# (=empty) mask & variance. 

# 2.2 If the user has not specified an HDU, or has specified one equal to the default: 

# 2.2.1 If the default HDU is unreadable, we throw. 

# 2.2.2 Otherwise, we attempt to read both mask and variance from the FITS file, 

# and return them together with the image. If one or both are unreadable, 

# we fall back to an empty default for the missing data and return the 

# remainder.. 

# 

# See also the discussion at DM-2599. 

 

def _checkMaskedImage(self, mim, width, height, val1, val2, val3): 

# Check that the input image has dimensions width & height and that the image, mask and 

# variance have mean val1, val2 & val3 respectively. 

self.assertEqual(mim.getWidth(), width) 

self.assertEqual(mim.getHeight(), width) 

self.assertEqual( 

afwMath.makeStatistics(mim.getImage(), afwMath.MEAN).getValue(), 

val1) 

s = afwMath.makeStatistics(mim.getMask(), afwMath.SUM | afwMath.NPOINT) 

self.assertEqual(float(s.getValue(afwMath.SUM)) / 

s.getValue(afwMath.NPOINT), val2) 

self.assertEqual( 

afwMath.makeStatistics(mim.getVariance(), afwMath.MEAN).getValue(), 

val3) 

 

def testUnreadableExtensionAsImage(self): 

# Test for case 2.1.1 above. 

with tmpFits(None, np.array([[1]]), np.array([[2]], dtype=np.int16), None) as fitsfile: 

self.assertRaises(Exception, self._constructImage, fitsfile, 3) 

 

def testReadableExtensionAsImage(self): 

# Test for case 2.1.2 above. 

with tmpFits(None, np.array([[1]]), np.array([[2]], dtype=np.int16), 

np.array([[3]])) as fitsfile: 

self._checkImage(self._constructImage(fitsfile, 3), 1, 1, 3, 0, 0) 

 

def testUnreadbleDefaultAsImage(self): 

# Test for case 2.2.1 above. 

with tmpFits(None, None, np.array([[2]], dtype=np.int16), np.array([[3]])) as fitsfile: 

self.assertRaises(Exception, self._constructImage, fitsfile) 

 

def testUnreadbleOptionalExtensions(self): 

# Test for case 2.2.2 above. 

# Unreadable mask. 

with tmpFits(None, np.array([[1]]), None, np.array([[3]])) as fitsfile: 

self._checkImage(self._constructImage(fitsfile), 1, 1, 1, 0, 3) 

# Unreadable variance. 

with tmpFits(None, np.array([[1]]), np.array([[2]], dtype=np.int16), None) as fitsfile: 

self._checkImage(self._constructImage(fitsfile, needAllHdus=False), 

1, 1, 1, 2, 0) 

 

 

class MaskedMultiExtensionTestCase(MultiExtensionTestCase, lsst.utils.tests.TestCase): 

"""Derived version of MultiExtensionTestCase for MaskedImages.""" 

 

def _constructImage(self, filename, hdu=None, needAllHdus=False): 

# Construct an instance of MaskedImageF by loading from filename. If hdu 

# is specified, load that HDU specifically. Pass through needAllHdus 

# to the MaskedImageF constructor. This function exists only to stub 

# default arguments into the constructor for parameters which we are 

# not exercising in this test. 

if hdu: 

filename = "%s[%d]" % (filename, hdu) 

return afwImage.MaskedImageF(filename, None, lsst.geom.Box2I(), afwImage.PARENT, False, needAllHdus) 

 

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

self._checkMaskedImage(*args, **kwargs) 

 

def testNeedAllHdus(self): 

# Tests for cases 1.1 & 1.2.2 above. 

# We'll regard it as ok for the user to specify any of: 

# * No HDU; 

# * The "zeroeth" (primary) HDU; 

# * The first (first extension) HDU. 

# Any others should raise when needAllHdus is true 

with tmpFits(None, np.array([[1]]), np.array([[2]], dtype=np.int16), 

np.array([[3]])) as fitsfile: 

# No HDU specified -> ok. 

self._checkImage(self._constructImage(fitsfile, needAllHdus=True), 

1, 1, 1, 2, 3) 

# First HDU -> ok. 

self._checkImage( 

self._constructImage(fitsfile, 0, needAllHdus=True), 

1, 1, 1, 2, 3) 

# First HDU -> ok. 

self._checkImage( 

self._constructImage(fitsfile, 1, needAllHdus=True), 

1, 1, 1, 2, 3) 

# Second HDU -> raises. 

self.assertRaises(Exception, self._constructImage, 

fitsfile, 2, needAllHdus=True) 

 

def testUnreadableImage(self): 

# Test for case 1.2.1 above. 

with tmpFits(None, None, np.array([[2]], dtype=np.int16), np.array([[3]])) as fitsfile: 

self.assertRaises(Exception, self._constructImage, 

fitsfile, None, needAllHdus=True) 

 

def testUnreadableMask(self): 

# Test for case 1.2.1 above. 

with tmpFits(None, np.array([[1]]), None, np.array([[3]])) as fitsfile: 

self.assertRaises(Exception, self._constructImage, 

fitsfile, None, needAllHdus=True) 

 

def testUnreadableVariance(self): 

# Test for case 1.2.1 above. 

with tmpFits(None, np.array([[1]]), np.array([[2]], dtype=np.int16), None) as fitsfile: 

self.assertRaises(Exception, self._constructImage, 

fitsfile, None, needAllHdus=True) 

 

 

class ExposureMultiExtensionTestCase(MultiExtensionTestCase, lsst.utils.tests.TestCase): 

"""Derived version of MultiExtensionTestCase for Exposures.""" 

 

def _constructImage(self, filename, hdu=None, needAllHdus=False): 

# Construct an instance of ExposureF by loading from filename. If hdu 

# is specified, load that HDU specifically. needAllHdus exists for API 

# compatibility, but should always be False. This function exists only 

# to stub default arguments into the constructor for parameters which 

# we are not exercising in this test. 

if hdu: 

filename = "%s[%d]" % (filename, hdu) 

if needAllHdus: 

raise Exception("Cannot needAllHdus with Exposure") 

return afwImage.ExposureF(filename) 

 

def _checkImage(self, im, width, height, val1, val2, val3): 

self._checkMaskedImage(im.getMaskedImage(), width, 

height, val1, val2, val3) 

 

 

class TestMemory(lsst.utils.tests.MemoryTestCase): 

pass 

 

 

def setup_module(module): 

lsst.utils.tests.init() 

 

 

424 ↛ 425line 424 didn't jump to line 425, because the condition on line 424 was never trueif __name__ == "__main__": 

lsst.utils.tests.init() 

unittest.main()