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

# 

# LSST Data Management System 

# Copyright 2008, 2009, 2010 LSST Corporation. 

# 

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

# 

 

import unittest 

 

import numpy as np 

 

import lsst.utils.tests 

import lsst.afw.image as afwImage 

import lsst.afw.math as afwMath 

from lsst.pipe.tasks.matchBackgrounds import MatchBackgroundsTask 

 

 

class MatchBackgroundsTestCase(unittest.TestCase): 

 

"""Background Matching""" 

 

def setUp(self): 

np.random.seed(1) 

 

# Make a few test images here 

# 1) full coverage (plain vanilla image) has mean = 50counts 

self.vanilla = afwImage.ExposureF(600, 600) 

im = self.vanilla.getMaskedImage().getImage() 

afwMath.randomGaussianImage(im, afwMath.Random('MT19937', 1)) 

im += 50 

self.vanilla.getMaskedImage().getVariance().set(1.0) 

 

# 2) has chip gap and mean = 10 counts 

self.chipGap = afwImage.ExposureF(600, 600) 

im = self.chipGap.getMaskedImage().getImage() 

afwMath.randomGaussianImage(im, afwMath.Random('MT19937', 2)) 

im += 10 

im.getArray()[:, 200:300] = np.nan # simulate 100pix chip gap 

self.chipGap.getMaskedImage().getVariance().set(1.0) 

 

# 3) has low coverage and mean = 20 counts 

self.lowCover = afwImage.ExposureF(600, 600) 

im = self.lowCover.getMaskedImage().getImage() 

afwMath.randomGaussianImage(im, afwMath.Random('MT19937', 3)) 

im += 20 

self.lowCover.getMaskedImage().getImage().getArray()[:, 200:] = np.nan 

self.lowCover.getMaskedImage().getVariance().set(1.0) 

 

# make a matchBackgrounds object 

self.matcher = MatchBackgroundsTask() 

self.matcher.config.usePolynomial = True 

self.matcher.binSize = 64 

self.matcher.debugDataIdString = 'Test Visit' 

 

self.sctrl = afwMath.StatisticsControl() 

self.sctrl.setNanSafe(True) 

self.sctrl.setAndMask(afwImage.Mask.getPlaneBitMask(["NO_DATA", "DETECTED", "DETECTED_NEGATIVE", 

"SAT", "BAD", "INTRP", "CR"])) 

 

def tearDown(self): 

self.vanilla = None 

self.lowCover = None 

self.chipGap = None 

self.matcher = None 

self.sctrl = None 

 

def checkAccuracy(self, refExp, sciExp): 

"""Check for accurate background matching in the matchBackgrounds Method. 

 

To be called by tests expecting successful matching. 

""" 

struct = self.matcher.matchBackgrounds(refExp, sciExp) 

resultExp = sciExp 

MSE = struct.matchedMSE 

diffImVar = struct.diffImVar 

 

resultStats = afwMath.makeStatistics(resultExp.getMaskedImage(), 

afwMath.MEAN | afwMath.VARIANCE, 

self.sctrl) 

resultMean, _ = resultStats.getResult(afwMath.MEAN) 

resultVar, _ = resultStats.getResult(afwMath.VARIANCE) 

refStats = afwMath.makeStatistics( 

refExp.getMaskedImage(), afwMath.MEAN | afwMath.VARIANCE, self.sctrl) 

refMean, _ = refStats.getResult(afwMath.MEAN) 

self.assertAlmostEqual(refMean, resultMean, delta=resultVar) # very loose test. 

# If MSE is within 1% of the variance of the difference image: SUCCESS 

self.assertLess(MSE, diffImVar * 1.01) 

 

# -=-=-=-=-=-=Test Polynomial Fit (Approximate class)-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 

 

def testConfig(self): 

"""Test checks on the configuration. 

 

1) Should throw ValueError if binsize is > size of image 

2) Need Order + 1 points to fit. Should throw ValueError if Order > # of grid points 

""" 

for size in range(601, 1000, 100): 

self.matcher.config.binSize = size 

self.assertRaises(ValueError, self.matcher.matchBackgrounds, self.chipGap, self.vanilla) 

 

# for image 600x600 and binsize 256 = 3x3 grid for fitting. order 3,4,5...should fail 

self.matcher.config.binSize = 256 

for order in range(3, 8): 

self.matcher.config.order = order 

self.assertRaises(ValueError, self.matcher.matchBackgrounds, self.chipGap, self.vanilla) 

 

for size, order in [(600, 0), (300, 1), (200, 2), (100, 5)]: 

self.matcher.config.binSize = size 

self.matcher.config.order = order 

self.checkAccuracy(self.chipGap, self.vanilla) 

 

def testInputParams(self): 

"""Test throws RuntimeError when dimensions don't match.""" 

self.matcher.config.binSize = 128 

self.matcher.config.order = 2 

# make image with wronge size 

wrongSize = afwImage.ExposureF(500, 500) 

wrongSize.getMaskedImage().getImage().set(1.0) 

wrongSize.getMaskedImage().getVariance().set(1.0) 

self.assertRaises(RuntimeError, self.matcher.matchBackgrounds, self.chipGap, wrongSize) 

 

def testVanillaApproximate(self): 

"""Test basic matching scenario with .Approximate.""" 

self.matcher.config.binSize = 128 

self.matcher.config.order = 4 

self.checkAccuracy(self.chipGap, self.vanilla) 

 

def testRampApproximate(self): 

"""Test basic matching of a linear gradient with Approximate.""" 

self.matcher.config.binSize = 64 

testExp = afwImage.ExposureF(self.vanilla, True) 

testIm = testExp.getMaskedImage().getImage() 

afwMath.randomGaussianImage(testIm, afwMath.Random()) 

nx, ny = testExp.getDimensions() 

dzdx, dzdy, z0 = 1, 2, 0.0 

for x in range(nx): 

for y in range(ny): 

z = testIm[x, y, afwImage.LOCAL] 

testIm[x, y, afwImage.LOCAL] = z + dzdx * x + dzdy * y + z0 

self.checkAccuracy(testExp, self.vanilla) 

 

def testLowCoverThrowExpectionApproximate(self): 

"""Test low coverage with .config.undersampleStyle = THROW_EXCEPTION. 

Confirm throws ValueError with Approximate. 

""" 

self.matcher.config.binSize = 64 

self.matcher.config.order = 8 

self.matcher.config.undersampleStyle = "THROW_EXCEPTION" 

self.assertRaises(ValueError, self.matcher.matchBackgrounds, self.chipGap, self.lowCover) 

 

def testLowCoverIncreaseSampleApproximate(self): 

"""Test low coverage with .config.undersampleStyle = INCREASE_NXNYSAMPLE. 

Confirm successful matching with .Approximate. 

""" 

self.matcher.config.binSize = 128 

self.matcher.config.order = 4 

self.matcher.config.undersampleStyle = "INCREASE_NXNYSAMPLE" 

self.checkAccuracy(self.chipGap, self.lowCover) 

 

def testLowCoverReduceInterpOrderApproximate(self): 

"""Test low coverage with .config.undersampleStyle = REDUCE_INTERP_ORDER. 

Confirm successful matching with .Approximate. 

""" 

self.matcher.config.binSize = 64 

self.matcher.config.order = 8 

self.matcher.config.undersampleStyle = "REDUCE_INTERP_ORDER" 

self.checkAccuracy(self.chipGap, self.lowCover) 

 

def testMasksApproximate(self): 

"""Test that masks are ignored in matching backgrounds: .Approximate.""" 

testExp = afwImage.ExposureF(self.chipGap, True) 

im = testExp.getMaskedImage().getImage() 

im += 10 

mask = testExp.getMaskedImage().getMask() 

satbit = mask.getPlaneBitMask('SAT') 

for i in range(0, 200, 20): 

mask[5, i, afwImage.LOCAL] = satbit 

im[5, i, afwImage.LOCAL] = 65000 

self.matcher.config.binSize = 128 

self.matcher.config.order = 4 

self.checkAccuracy(self.chipGap, testExp) 

 

def testWeightsByInvError(self): 

"""Test that bins with high std.dev. and low count are weighted less in fit.""" 

testExp = afwImage.ExposureF(self.chipGap, True) 

testIm = testExp.getMaskedImage().getImage() 

self.matcher.config.binSize = 60 

self.matcher.config.order = 4 

for x in range(0, 50): 

for y in range(0, 50): 

if np.random.rand(1)[0] < 0.6: 

testIm[x, y, afwImage.LOCAL] = np.nan 

else: 

testIm[x, y, afwImage.LOCAL] = np.random.rand()*1000 

 

self.matcher.matchBackgrounds(self.vanilla, testExp) 

resultExp = testExp 

resultArr = resultExp.getMaskedImage().getImage().getArray()[60:, 60:] 

resultMean = np.mean(resultArr[np.where(~np.isnan(resultArr))]) 

resultVar = np.std(resultArr[np.where(~np.isnan(resultArr))])**2 

self.assertAlmostEqual(50, resultMean, delta=resultVar) # very loose test. 

 

def testSameImageApproximate(self): 

"""Test able to match identical images: .Approximate.""" 

vanillaTwin = afwImage.ExposureF(self.vanilla, True) 

self.matcher.config.binSize = 128 

self.matcher.config.order = 4 

self.checkAccuracy(self.vanilla, vanillaTwin) 

 

# -=-=-=-=-=-=-=-=-=Background Interp (Splines) -=-=-=-=-=-=-=-=- 

 

def testVanillaBackground(self): 

"""Test basic matching scenario with .Background.""" 

self.matcher.config.usePolynomial = False 

self.matcher.config.binSize = 128 

self.checkAccuracy(self.chipGap, self.vanilla) 

 

def testRampBackground(self): 

"""Test basic matching of a linear gradient with .Background.""" 

self.matcher.config.usePolynomial = False 

self.matcher.config.binSize = 64 

testExp = afwImage.ExposureF(self.vanilla, True) 

testIm = testExp.getMaskedImage().getImage() 

afwMath.randomGaussianImage(testIm, afwMath.Random()) 

nx, ny = testExp.getDimensions() 

dzdx, dzdy, z0 = 1, 2, 0.0 

for x in range(nx): 

for y in range(ny): 

z = testIm[x, y, afwImage.LOCAL] 

testIm[x, y, afwImage.LOCAL] = z + dzdx * x + dzdy * y + z0 

self.checkAccuracy(testExp, self.vanilla) 

 

def testUndersampleBackgroundPasses(self): 

"""Test undersample style (REDUCE_INTERP_ORDER): .Background. 

 

INCREASE_NXNYSAMPLE no longer supported by .Background because .Backgrounds's are 

defined by their nx and ny grid. 

""" 

self.matcher.config.usePolynomial = False 

self.matcher.config.binSize = 256 

self.matcher.config.undersampleStyle = "REDUCE_INTERP_ORDER" 

self.checkAccuracy(self.chipGap, self.vanilla) 

 

self.matcher.config.undersampleStyle = "INCREASE_NXNYSAMPLE" 

self.assertRaises(RuntimeError, self.matcher.matchBackgrounds, self.chipGap, self.vanilla) 

 

def testSameImageBackground(self): 

"""Test able to match identical images with .Background.""" 

self.matcher.config.usePolynomial = False 

self.matcher.config.binSize = 256 

self.checkAccuracy(self.vanilla, self.vanilla) 

 

def testMasksBackground(self): 

"""Test masks ignored in matching backgrounds with .Background.""" 

self.matcher.config.usePolynomial = False 

self.matcher.config.binSize = 256 

testExp = afwImage.ExposureF(self.chipGap, True) 

im = testExp.getMaskedImage().getImage() 

im += 10 

mask = testExp.getMaskedImage().getMask() 

satbit = mask.getPlaneBitMask('SAT') 

for i in range(0, 200, 20): 

mask[5, i, afwImage.LOCAL] = satbit 

im[5, i, afwImage.LOCAL] = 65000 

self.checkAccuracy(self.chipGap, testExp) 

 

def testChipGapHorizontalBackground(self): 

""" Test able to match image with horizontal chip gap (row of nans) with .Background""" 

self.matcher.config.usePolynomial = False 

self.matcher.config.binSize = 64 

chipGapHorizontal = afwImage.ExposureF(600, 600) 

im = chipGapHorizontal.getMaskedImage().getImage() 

afwMath.randomGaussianImage(im, afwMath.Random()) 

im += 10 

im.getArray()[200:300, :] = np.nan # simulate 100pix chip gap horizontal 

chipGapHorizontal.getMaskedImage().getVariance().set(1.0) 

self.checkAccuracy(self.vanilla, chipGapHorizontal) 

 

def testChipGapVerticalBackground(self): 

""" Test able to match images with vertical chip gaps (column of nans) wider than bin size""" 

self.matcher.config.usePolynomial = False 

self.matcher.config.binSize = 64 

self.checkAccuracy(self.chipGap, self.vanilla) 

 

def testLowCoverBackground(self): 

""" Test able to match images that do not cover the whole patch""" 

self.matcher.config.usePolynomial = False 

self.matcher.config.binSize = 64 

self.checkAccuracy(self.vanilla, self.lowCover) 

 

 

def setup_module(module): 

lsst.utils.tests.init() 

 

 

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

pass 

 

 

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

lsst.utils.tests.init() 

unittest.main()